java 解析 json 字符串 一般使用 fastjson 进行操作,即导入以下依赖即可
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
// hutool 工具包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.4</version>
</dependency>
例如需要解析 json 字符串 为
{
"error": 0,
"status": "success",
"results": [
{
"currentCity": "青岛",
"index": [
{
"title": "穿衣",
"zs": "较冷",
"tipt": "穿衣指数",
"des": "建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。"
},
{
"title": "紫外线强度",
"zs": "中等",
"tipt": "紫外线强度指数",
"des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"
}
]
}
]
}
解析如下:
String json= HttpUtil.createGet(url).execute().body();
JSONObject jsonObject = JSONObject.parseObject(json);
String error = jsonObject.getString("error");
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.size(); i++) {
String currentCity = results.getJSONObject(i).getString("currentCity");
JSONArray index = results.getJSONObject(i).getJSONArray("index");
for (int j = 0; j < index.size(); j++) {
String title = index.getJSONObject(j).getString("title");
String zs = index.getJSONObject(j).getString("zs");
String tipt = index.getJSONObject(j).getString("tipt");
String des = index.getJSONObject(j).getString("des");
}
}
|