首先,可以使用Online JSON Viewer工具清晰地查看JSON的具体结构。
https://www.bejson.com/jsonviewernew/
让我们拿这段JSON文本来举例子吧:
{"code":"200","updateTime":"2021-08-06T02:17+08:00","fxLink":"http://hfx.link/2ax1","now":{"obsTime":"2021-08-06T02:12+08:00","temp":"23","feelsLike":"24","icon":"101","text":"多云","wind360":"135","windDir":"东南风","windScale":"2","windSpeed":"8","humidity":"79","precip":"0.0","pressure":"1001","vis":"19","cloud":"91","dew":"21"},"refer":{"sources":["Weather China"],"license":["no commercial use"]}}
格式化后:
{
"code": "200",
"updateTime": "2021-08-06T02:17+08:00",
"fxLink": "http://hfx.link/2ax1",
"now": {
"obsTime": "2021-08-06T02:12+08:00",
"temp": "23",
"feelsLike": "24",
"icon": "101",
"text": "多云",
"wind360": "135",
"windDir": "东南风",
"windScale": "2",
"windSpeed": "8",
"humidity": "79",
"precip": "0.0",
"pressure": "1001",
"vis": "19",
"cloud": "91",
"dew": "21"
},
"refer": {
"sources": [
"Weather China"
],
"license": [
"no commercial use"
]
}
}
在 Online Json Viewer 中的视图如下:
重要总结:
前面图标为 { } 的项所对应的 Class 为: JSONObject
前面图标为 [ ] 的项所对应的 Class 为: JSONArray
前面图标为 方块 的项所对应的 Class中的方法 为: JSONObject.getT() 或 JSONArray.getT()
Java 示例:
下面的代码用来获取 license.0 对应的文本(String)值
//主类代码省略
String json = "JSON文本, 此处略";
JSONObject obj = JSON.parseObject(json);
JSONObject obj_refer = obj.getJSONObject("refer"); //refer
JSONArray arr_license = obj_refer.getJSONArray("license"); //refer.license
String str_license = arr_license.getString(0); //refer.license.0
System.out.println(str_license);
示例输出:
no commercial use