5

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.

2
  • Do you need to get all the keys in JSONObject? Commented Apr 20, 2015 at 10:01
  • Yes, all the keys with their respective values. Commented Apr 20, 2015 at 10:02

4 Answers 4

16

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);
  }
Sign up to request clarification or add additional context in comments.

6 Comments

+1 for letting me know about the keys idea. I have edited my answer and considered the iterator solution to the Hashtable
Hi this is working fine for 5+ versions. On kitkat 4.4 it give wrong sequence.What should I do?
@SAndroidD: As you know JSONObject is unordered collection. let me know which issue you are getting currently
actually My JSONObject collection in proper format. But when I get keys in Iterator these are not in sequence. For android version 5+ working perfect
@SAndroidD: Ok Why order is important? please share link if you posted any question
|
12

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;
    }
}

Comments

1

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 = new Hashtable<>();

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

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

Or using Iterator as the following example :

Map<Integer, String> results = new Hashtable<>();

    try {
        //The response is your JSON as a string
        JSONObject obj = new JSONObject(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 results
    return results;

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

1 Comment

Thanks for replying. I'm using custom class(bean) for storing list of categories instead of HashMap
0

Try out this code

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

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

        String value= obj.getString(dynamicKey);
    }

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.