Java解析复杂的JSON数据
复杂的JSON数据
// Java里的json数据
JSONObject jsonObject = {
"code": "10000",
"charge": false,
"msg": "查询成功",
"result": {
"HeWeather5": [{
"daily_forecast": [{
"astro": {
"mr": "11:34",
"ms": "22:36",
"sr": "06:57",
"ss": "16:17"
},
"cond": {
"code_d": "100",
"code_n": "100",
"txt_d": "晴",
"txt_n": "晴"
},
"date": "2018-12-14",
"hum": "46",
"pcpn": "0.0",
"pop": "0",
"pres": "1039",
"tmp": {
"max": "-2",
"min": "-10"
}
}],
"status": "ok"
}]
}
}
Java获取高低气温,也就是上面的tmp里面的值
//Java代码,jsonObject为上面代码json数据的名字
JSONObject a = jsonObject.getJSONObject("result");
JSONArray b = a.getJSONArray("HeWeather5");
JSONObject c = b.getJSONObject(0);
JSONArray d = c.getJSONArray("daily_forecast");
JSONObject e = d.getJSONObject(0);
JSONObject f = e.getJSONObject("tmp");
String g = f.getString("max");//最高气温
String h = f.getString("min");//最低气温
这样就可以获取到高低气温了。需要一层一层的取。如果某一层是对象就使用getJSONObject()方法,如果某一层的结果是数组,就使用getJSONArray()方法。