Atul Mavani Atul Mavani - 5 months ago 41
Android Question

parsing nested json object in android

How do I parse Json data when the Json response data is returned in nested Json object form.

I looked at this post which shows how to get only one piece of data. As I want whole data set it is not useful for me.

It said:

JSONObject jMainObject = null;
try {
jMainObject = new JSONObject(jsonString);
JSONObject apiGroupsObject = jMainObject.getJSONObject("apiGroups");
JSONObject affiliateObject = apiGroupsObject.getJSONObject("affiliate");
JSONObject apiListingsObject = affiliateObject.getJSONObject("apiListings");
JSONObject bags_wallets_beltsObject = apiListingsObject.getJSONObject("bags_wallets_belts");
JSONObject availableVariantsObject = bags_wallets_beltsObject.getJSONObject("availableVariants");
JSONObject versionObject = availableVariantsObject.getJSONObject("v0.1.0");
System.out.println(versionObject);
} catch (JSONException e) {
e.printStackTrace();
}


The Json returned data which I want to parse is coming from here.

Can anyone help me to solve my problem about how to parse this type of data as I’m new so I don’t know how to parse nested Json object data. Perhaps I can use Gson for it? But I also don't know how to use that.

Answer
do it like this, hope it will help you, tested    

JSONObject objresponse = new JSONObject(response);
                    JSONObject objapiGroups = objresponse.getJSONObject("apiGroups");
                    JSONObject objaffiliate = objapiGroups.getJSONObject("affiliate");
                    JSONObject objapiListings = objaffiliate.getJSONObject("apiListings");

                    Iterator iterator = objapiListings.keys();
                    int i=0;
                    Catagory=new String[objapiListings.length()];
                    while(iterator.hasNext()){
                        String key = (String)iterator.next();
                        JSONObject issue = objapiListings.getJSONObject(key);

                        //  get id from  issue
                        Catagory[i] = issue.optString("apiName");
                        i++;
                    }
                    JSONObject[] objcat = new JSONObject[Catagory.length];
                    CatagoryName=new String[Catagory.length];
                    Url=new String[Catagory.length];
                    for(int j=0;j<Catagory.length;j++)
                    {
                        objcat[j]=objapiListings.getJSONObject(Catagory[j]);

                        CatagoryName[j]=objcat[j].getJSONObject("availableVariants").getJSONObject("v1.1.0").getString("resourceName");
                        Url[j]=objcat[j].getJSONObject("availableVariants").getJSONObject("v1.1.0").getString("get");

                    }