如何从嵌套的JSON响应中检索信息?

时间:2012-01-20 17:55:16

标签: java android

我正在检索JSON响应,除了一个部分之外没有任何问题。有些项是嵌套的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"
            }
        }
    ]
}

}

如何访问联系人对象中的一个项目,例如" formattedPhone"?

我可以访问"名称"每个项目的罚款:

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");          
}

1 个答案:

答案 0 :(得分:0)

以下是我如何解决它,因为在某些情况下不存在联系:

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();
}