简体   繁体   中英

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

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 ?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM