简体   繁体   中英

How do I retrieve info from a nested JSON response?

I'm retrieving a JSON response and have no problems except for one part. Some items are nested JSONObjects:

{
"response": {
    "venues": [
        {
            "id": "42829c80f964a5205f221fe3",
            "name": "AmericanExpressTower",
            "contact": {
                "phone": "2126405130",
                "formattedPhone": "(212)640-5130",
                "twitter": "americanexpress"
            },
            "location": {
                "address": "200VeseySt",
                "crossStreet": "WestSt",
                "lat": 40.713618978735,
                "lng": -74.01408649911748,
                "distance": 1926,
                "postalCode": "10285",
                "city": "NewYork",
                "state": "NY",
                "country": "UnitedStates"
            }
        }
    ]
}

}

How can I access one item in the contact object like "formattedPhone"?

I can access the "name" of each item fine:

JSONObject json = new JSONObject(result);  

JSONArray venues = json.getJSONObject("response")
      .getJSONArray("venues"); 
input.close();  
int vLength = venues.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < vLength; i++) {
  builder.append("Location: ");
  builder.append(venues.getJSONObject(i)
      .getString("name").toString());    
  builder.append("\n");          
}

Here is how I solved it since contact doesn't exist in some cases:

try {
    JSONObject contacts = new JSONObject(venues.getJSONObject(i).getString("contact"));
    builder.append("Phone: ");
    builder.append(contacts.get("formattedPhone")); 
    builder.append("\n"); 
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

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