简体   繁体   中英

accessing nested list in JSONArray

I have created a JSONObject from a raw JSON string. Then I created a JSONArray from it. I am trying to access the "location" list for each index of the JSONArray because I need the "location" information for the Location constructor. 在此处输入图片说明

This is what I have so far

try
{
    //create a JSON Object with the raw string
    JSONObject json=new JSONObject(responseData);
    //create array of businesses
    JSONArray arr=json.getJSONArray("businesses");
    for(int i=0;i<arr.length();i++)
    {
        //I need "location" info here
        locations.add(new Location(arr.getJSONObject(i).getString("id"),arr.getJSONObject(i).getString("name"), arr.getJSONObject(i).getString("image_url"),"placeholder",0));
    }
}
catch (JSONException e)
{
    e.printStackTrace();
}

Ok my answer was more than obvious but somehow I complicated myself. This worked for me.

for(int i=0;i<arr.length();i++)
{
    JSONObject loc=arr.getJSONObject(i).getJSONObject("location");
    locations.add(new Location(arr.getJSONObject(i).getString("id"), arr.getJSONObject(i).getString("name"), arr.getJSONObject(i).getString("image_url"),loc.getString("address1")+" "+ loc.getString("address2")+","+loc.getString("city")+","+loc.getString("zip_code"),0));
}

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