0

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

2 Comments

JSONObject innsersubObj = subArrayObj.getJSONObject("item");
Yes, it will show an error.. Bec you have to use index of an array then you can fetch "item".. You can use a for loop and use get JSONOBJECT (i) method to do so.. Then inside loop u can have "item" which will again return an array.. So, basically use the correct classes by seeing the R.H.S that what it is returning.

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.