user
user

Reputation: 471

How to parse multiple JSON object inside JSON object?

I am trying to parse a JSON Response which is containing multiple JSON objects. Here is my code:

{
"All": {
    "name": "All",
    "display": "All"
},
"Apparel": {
    "name": "Apparel",
    "display": "Apparel"
},
"Appliances": {
    "name": "Appliances",
    "display": "Appliances"
}
}

I had tried single object parsing response in Json, that I able to fetch. But I don't not know how to parse the Json object with Multiple nodes. I had tried, but could not able to succeed in this.

Upvotes: 2

Views: 2097

Answers (4)

Ravi Kant
Ravi Kant

Reputation: 830

You can try below code

JSONObject outer = new JSONObject(response);
Iterator<String> keys =outer.keys();
while(keys.hasNext()){
    String key = keys.next();
    JSONObject inside = outer.getJSONObject(key);
    //Do stuff
}

where response is json string.

Upvotes: 1

Ohad Zadok
Ohad Zadok

Reputation: 3620

You can just get another JSONObect as the value to the key requested, Try that:

String jsonStr = " {\n\"All\": {\n    \"name\": \"All\",\n    \"display\": \"All\"\n},\n\"Apparel\": {\n    \"name\": \"Apparel\",\n    \"display\": \"Apparel\"\n},\n\"Appliances\": {\n    \"name\": \"Appliances\",\n    \"display\": \"Appliances\"\n}";
JSONObject json;
json = new JSONObject(jsonStr);
JSONObject All = json.getJSONObject("All");

Upvotes: 1

Dakshesh Khatri
Dakshesh Khatri

Reputation: 629

try {
            JSONObject obj = new JSONObject("your result String");
            JSONObject obj1 = obj.getJSONObject("All");
            String name=obj1.getString("name");
            String display=obj1.getString("display");
            JSONObject obj2 = obj.getJSONObject("Apparel");
            String name1=obj2.getString("name");
            String display1=obj2.getString("display");

            JSONObject obj3 = obj.getJSONObject("Appliances");
            String name2=obj3.getString("name");
            String display2=obj3.getString("display");


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Upvotes: 1

Maneesh
Maneesh

Reputation: 6128

It will be like this as below. where RootData is main json string

JSONObject js=new JSONObject(RootData);
JSONObject all =js.getJSONObject(“All”);
String AllName=all.getString(“name”);
String AllDisplay=all.getString(“display”);

JSONObject apparel =js.getJSONObject(“Apparel”);
String apparel_Name=apparel .getString(“name”);
String apparel_Display=apparel .getString(“display”);

JSONObject appliances =js.getJSONObject(“Appliances”);
String appliances_Name=appliances .getString(“name”);
String appliances_Display=appliances .getString(“display”);

Upvotes: 1

Related Questions