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:
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.
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);
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With