Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSONObject having dynamic key

Tags:

json

android

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": "World",
        "2": "Politics",
        "3": "Economy",
        "4": "Sports",
        "5": "Cricket",
        "6": "General",
        "7": "Business",
        "8": "Services",
        "9": "Law & Order",
        "10": "Entertainment"
    }
}

Validation: JSON Validatiion

If it would have been JSONArray, I would have parsed it with this solution from SO: How to parse a JSON without key in android?

But how do I parse the JSON I have here?

Any help appreciated.

like image 420
GAMA Avatar asked Apr 20 '15 09:04

GAMA


2 Answers

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=new JSONObject(<json_string>);
// get category JSONObject from mainJSONObj
JSONObject categoryJSONObj=mainJSONObj.getJSONObject("category");

// get all keys from categoryJSONObj

Iterator<String> iterator = categoryJSONObj.keys();
  while (iterator.hasNext()) {
    String key = iterator.next();
    Log.i("TAG","key:"+key +"--Value::"+categoryJSONObj.optString(key);
  }
like image 85
ρяσѕρєя K Avatar answered Nov 09 '22 04:11

ρяσѕρєя K


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

class MyClass {
    @SerializedName("category")
    private Map<String, String> categories;

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

    public void setCategories(Map<String, String> categories) {
        this.categories = categories;
    }
}
like image 33
rasmeta Avatar answered Nov 09 '22 06:11

rasmeta