How to parse json data which has multiple jsonArrays in android?

64 views Asked by At

I have JSON data like this,it is having multiple jsonArrays in it.how to parse this type of data?

{
        "result":
        [{
        "site_name":"comenius",
        "ws_url":"https://comenius-api.sabacloud.com/v1/",
        "base_url":"https://comenius.sabacloud.com/",
        "logo_url":"",
        "Title":"",
        "menu_items":[
                {"item": 
                    [{"id":"home1","label":"Home" }]
                    },
                {"item":    
                    [{"id":"enrol1","label":"Enrollment" }]
                },
                {"item":
                   [{"id":"transcripts1","label":"Completed Courses"}]
                },
                {"item":
                   [{"id":"goals1","label":"Goals"}]
                },
                {"item":
                    [{"id":"rprojects1","label":"Reference Projects"}]
                },
                {"item":
                      [{"id":"iwh1","label":"Internal Work History"}]
                },
                {"item":
                     [{"id":"ewh1","label":"EXternal Work History"}]
                }
                ]
        },{.....}
 ]
 }

i need to parse the data and get the values of id,label ,i write some code to parse the data but it didnt work.

  JSONObject subObj = new JSONObject(data2);
  JSONObject innerObj1 = subObj.getJSONObject("result");
  JSONObject subArrayObj = innerObj1.getJSONObject("menu_items");
  for(int j =0;j < subArrayObj.length();j++) {
  JSONObject innsersubObj = subArrayObj.getJSONObject("item");
  String id = innsersubObj.getString("id");
  String label = innsersubObj.getString("label");
  Log.e("id",id);
  Log.e("label",label);
   }

How to parse the data any thing need to change in the code ?

2

There are 2 answers

0
Okas On BEST ANSWER

You have to use JSONObject and JSONArray are different objects, you have to use correct class:

JSONArray resultArray = subObj.getJSONArray("result");
JSONObject firstItem = resultArray.getJSONObject(0);
JSONArray menuItems = firstItem.getJSONArray("menu_items");

etc.

2
Ankit On

JSONARRAY subArrayObj = innerObj1.getJSONARRAY("menu_items");

Since menu_items is returning an array..it should be collected in an array object..