2014-07-23 108 views
0

如果我的JSON對象看起來是這樣的:如何在Android中使用java訪問嵌套的JSON數據?

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

我將如何訪問這個城市叫什麼名字?我可以使用optString來獲取所有「天氣」或「評級」,但是如何獲取其中的信息?

回答

3

這很簡單

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

閱讀上JSONObject

+0

http://developer.android.com/reference/org/json/JSONObject.html – Robert

+0

@Robert感謝羅伯特我加了鏈接 – meda

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"); //... 
0
JSONObject obj = new JSONObject(jsonString); 
JSONObject weatherObj = obj.getJSONObject("weather"); 
JSONObject locationObj = weatherObj.getJSONObject("location"); 
String city = locationObj.getString("city"); //new york 
相關問題