这是我的JSON
,
{
"city": {
"id": 2961297,
"name": "Swords",
"coord": {
"lon": -6.21806,
"lat": 53.459721
},
"country": "IE",
"population": 0
},
"cod": "200",
"message": 0.3535,
"cnt": 1,
"list": [
{
"dt": 1481025600,
"temp": {
"day": 284.68,
"min": 284.68,
"max": 285.36,
"night": 285.36,
"eve": 284.8,
"morn": 284.68
},
"pressure": 1028.26,
"humidity": 95,
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"speed": 9.01,
"deg": 186,
"clouds": 92,
"rain": 0.5
}
]
}
我正在尝试访问降雨量"下雨":0.5,如上面返回的JSON
数据中所示,我不确定如何做到这一点因为我没有多少使用JSON
数据的经验。
这是我的代码,
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray ListArray = topLevel.getJSONArray("list");
weather = String.valueOf(ListArray);
for(int x = 0;x < ListArray.length();x++) {
JSONObject myObj = ListArray.getJSONObject(x);
myObj.getInt("rain");
Log.d("TODAYS Rain"+rain,"");
//System.out.Print("Current Weather" +id+main+icon+dscription+rain);
}
非常感谢任何帮助。
答案 0 :(得分:3)
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray listArray = topLevel.getJSONArray("list");
JSONObject firstObject = (JSONObject)listArray.get(0);
Double rain = firstObject.getDouble("rain");
System.out.println("TODAYs rain :" + rain);
}
答案 1 :(得分:3)
最简单的方法是解析Json是使用将Json映射到对象实例的POJO类。
您可以定义类结构,并使用检索到的数据填充它。
本网站上有关于同一主题的指南:http://www.ssaurel.com/blog/learn-how-to-parse-json-in-android-with-gson/
答案 2 :(得分:0)
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray ListArray = topLevel.getJSONArray("list");
weather = String.valueOf(ListArray);
for(int x = 0;x < ListArray.length();x++) {
JSONObject myObj = ListArray.getJSONObject(x);
myObj.getDouble("rain");
Log.d("TODAYS Rain"+rain,"");
//System.out.Print("Current Weather" +id+main+icon+dscription+rain);
}
你只需要使用myobj.getDouble(&#34; rain&#34;)而不是myobj.getInt(&#34; rain&#34;),因为rain的值不是整数。