Android 解析复杂JSON
学习自:自学。
Overview
今天在学实例的时候想要使用和风天气的开发API添加一个天气模块。
但是在我的到JSON 数据的时候我没有解析出来,但是我发现他是一个JSON数组,但是网上很多方法都是使用Gson去解析的,但是的开发环境不允许我使用Gson去开发,所以我通过JSONObject和JSONArray去进行解析。
先来看一下我们的和风天气返回的代码
{
"HeWeather6": [
{
"basic": {
"cid": "CN101190401",
"location": "苏州",
"parent_city": "苏州",
"admin_area": "江苏",
"cnty": "中国",
"lat": "31.29937935",
"lon": "120.61958313",
"tz": "+8.00"
},
"update": {
"loc": "2019-12-27 14:42",
"utc": "2019-12-27 06:42"
},
"status": "ok",
"now": {
"cloud": "10",
"cond_code": "100",
"cond_txt": "晴",
"fl": "5",
"hum": "49",
"pcpn": "0.0",
"pres": "1026",
"tmp": "8",
"vis": "6",
"wind_deg": "199",
"wind_dir": "西南风",
"wind_sc": "2",
"wind_spd": "8"
}
},
{
"basic": {
"cid": "CN101220701",
"location": "宿州",
"parent_city": "宿州",
"admin_area": "安徽",
"cnty": "中国",
"lat": "33.63389206",
"lon": "116.98408508",
"tz": "+8.00"
},
"update": {
"loc": "2019-12-27 14:42",
"utc": "2019-12-27 06:42"
},
"status": "ok",
"now": {
"cloud": "0",
"cond_code": "100",
"cond_txt": "晴",
"fl": "5",
"hum": "47",
"pcpn": "0.0",
"pres": "1021",
"tmp": "9",
"vis": "13",
"wind_deg": "210",
"wind_dir": "西南风",
"wind_sc": "3",
"wind_spd": "17"
}
},
{
"basic": {
"cid": "CN101160802",
"location": "肃州",
"parent_city": "酒泉",
"admin_area": "甘肃",
"cnty": "中国",
"lat": "39.74385834",
"lon": "98.51115417",
"tz": "+8.00"
},
"update": {
"loc": "2019-12-27 14:42",
"utc": "2019-12-27 06:42"
},
"status": "ok",
"now": {
"cloud": "0",
"cond_code": "100",
"cond_txt": "晴",
"fl": "-2",
"hum": "23",
"pcpn": "0.0",
"pres": "852",
"tmp": "1",
"vis": "16",
"wind_deg": "33",
"wind_dir": "东北风",
"wind_sc": "2",
"wind_spd": "6"
}
}
]
}
这个就是我们和风天气返回的JSON 文件了。
是不是看着就复杂,反正我是这么觉得。
那么我们看一下如何去解析他:
解析JSON
先来看一下源代码:
new Thread(new Runnable() {
@Override
public void run() {
String weatherJson = GetWeather();
try {
JSONObject jsonObject = new JSONObject(weatherJson);
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather6");
JSONObject JsonNow = jsonArray.getJSONObject(0).getJSONObject("now");
final String fl = JsonNow.getString("fl");
final String tmp = JsonNow.getString("tmp");
final String weather_txtData = JsonNow.getString("cond_txt");
final String wind_dir = JsonNow.getString("wind_dir");
final String wind_spd = JsonNow.getString("wind_sc");
JSONObject JsonBasic = jsonArray.getJSONObject(0).getJSONObject("basic");
final String location = JsonBasic.getString("location");
runOnUiThread(new Runnable() {
@Override
public void run() {
txtfl.setText("体感温度:" + fl);
txtlocation.setText("查询地区:" + location);
txttmp.setText("天气温度:" + tmp);
txtWeatherText.setText("天气情况:" + weather_txtData);
txtwinddir.setText("风向:" + wind_dir);
txtwindspd.setText("风力:" + wind_spd);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
这里我只给出了解析JSON的代码,关于如何获取JSON数据我不管。
我们仔细地看看JSON 元数据。
他在HeWeather6中包含了一个数组,然后先获取到对应地数组。
然后通过指定的名字取获取你需要的值。