Skip to content Skip to sidebar Skip to footer

Parsing Jsonobject Having Dynamic Key

I have following JSON as response from my server. At first, I thought, it was invalid JSON but after validating it, it seems to be correct: JOSN: { 'category': { '1': '

Solution 1:

But how do I parse the JSON I have here?

if keys inside category JSONObject is dynamic then use JSONObject.keys() to get Iterator for getting values as:

JSONObject mainJSONObj=newJSONObject(<json_string>);
// get category JSONObject from mainJSONObjJSONObject categoryJSONObj=mainJSONObj.getJSONObject("category");

// get all keys from categoryJSONObjIterator<String> iterator = categoryJSONObj.keys();
  while (iterator.hasNext()) {
    String key = iterator.next();
    Log.i("TAG","key:"+key +"--Value::"+categoryJSONObj.optString(key);
  }

Solution 2:

Try using gson deserialization with an object of such class as a serialization output class:

classMyClass {
    @SerializedName("category")
    privateMap<String, String> categories;

    publicMap<String, String> getCategories() {
       return categories;
    }

    publicvoidsetCategories(Map<String, String> categories) {
        this.categories = categories;
    }
}

Solution 3:

If I were you and I'm sure that the keys are a sequence of numbers starting with 1, I would do the following:

Map<Integer, String> results = newHashtable<>();

    try {
        //The response is your JSON as a stringJSONObject obj = newJSONObject(response);
        JSONObject categories = obj.getJSONObject("categories");

        int counter = 1;
        //Breakable infinite loop, will be broken when you try to get non existing itemwhile(true){
            results.put(counter, categories.getString(counter+""));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
//Return the map that contain the resultsreturn results;

Or using Iterator as the following example :

Map<Integer, String> results = newHashtable<>();

    try {
        //The response is your JSON as a stringJSONObject obj = newJSONObject(response);
        JSONObject categories = obj.getJSONObject("categories");

        Iterator<String> iter = categories.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            results.put(key, categories.getString(key+""));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Return the map that contain the resultsreturn results;

You can also create an ArrayList<String> and add the values to it instead of adding them to a HashTable

Solution 4:

Try out this code

JSONObject obj = result.getJSONObject("category");
    Iterator keys = obj.keys();

    while (keys.hasNext()) {
        // loop to get the dynamic keyString dynamicKey = (String) keys.next();

        String value= obj.getString(dynamicKey);
    }

For more information checkout this link. May be this will help you more.

Post a Comment for "Parsing Jsonobject Having Dynamic Key"