如何使用java访问android中的嵌套JSON数据?

时间:2014-07-23 17:53:02

标签: java android json

如果我的JSON对象看起来像这样:

{
 "weather:{
   "sunny": "yes"
   "wind": "48mph"
   "location":{
     "city": "new york"
     "zip": "12345"
   }
 }
 "rating": "four stars"
}

我如何访问城市名称?我可以使用optString获取所有“天气”或“评级”,但我如何获取其中的信息?

3 个答案:

答案 0 :(得分:3)

非常简单

JSONObject jsonObj = new JSONObject(jsonString);
JSONObject weather = jsonObj.getJSONObject("weather");
JSONObject location = weather.getJSONObject("location");
String city = location.getString("city");

阅读JSONObject

答案 1 :(得分:0)

JSONObject json = new JSONObject(yourdata); 
JSONObject weather = json.getString("weather");
weather.getString("sunny"); //yes
weather.getString("wind"); //46mph

JSONObject location = new JSONObject(weather.getString("location"));
location.getString("city"); // new york

json.getString("rating"); //... 

答案 2 :(得分:0)

JSONObject obj = new JSONObject(jsonString);
JSONObject weatherObj = obj.getJSONObject("weather");
JSONObject locationObj = weatherObj.getJSONObject("location");
String city = locationObj.getString("city"); //new york