1. 什么是JSON?
2. 导入maven依赖
<!-- 解析json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
3. JSON案例文件
{
"sites": {
"site": [
{
"id": "1",
"name": "菜鸟教程",
"url": "www.runoob.com"
},
{
"id": "2",
"name": "菜鸟工具",
"url": "c.runoob.com"
},
{
"id": "3",
"name": "Google",
"url": "www.google.com"
},
{
"id": "4",
"name": "baidu",
"url": "www.baidu.com"
}
]
}
}
4. 示例代码
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;
public class 解析json {
public static void main(String[] args) throws IOException {
// 获取文件路径
String jsonpath = 解析json.class.getClassLoader().getResource("testjson.json").getPath();
// 读取文件获取内容
BufferedReader reader = new BufferedReader(new FileReader(jsonpath));
StringBuilder builder = new StringBuilder();
String line ;
while ((line = reader.readLine()) != null){
builder.append(line);
}
// 使用JSON 工具转换为对象
JSONObject jsonObject = JSON.parseObject(builder.toString());
// 获取所有的key
Set<String> keys = jsonObject.keySet();
// 根据所有的key获取value
for (String key : keys) {
System.out.println(key);
}
// 获取单个value, 这里根据JSON的结构, 逐层解析
String sites = jsonObject.get("sites").toString();
System.out.println(sites);
// 继续获取内部的内容, 将sites 解析成JSON对象
JSONObject parseObject = JSON.parseObject(sites);
// 内部的site 中的value为数组, 这里可以直接获取JSONArray
JSONArray jsonArray = parseObject.getJSONArray("site");
for (Object o : jsonArray) {
// 每一个元素又是对象
JSONObject jo = JSONObject.parseObject(o.toString());
System.out.println(jo.getString("id"));
System.out.println(jo.getString("name"));
System.out.println(jo.getString("url"));
}
}
}
5. 解析结果
sites
{"site":[{"name":"菜鸟教程","id":"1","url":"www.runoob.com"},{"name":"菜鸟工具","id":"2","url":"c.runoob.com"},{"name":"Google","id":"3","url":"www.google.com"},{"name":"baidu","id":"4","url":"www.baidu.com"}]}
1
菜鸟教程
www.runoob.com
2
菜鸟工具
c.runoob.com
3
Google
www.google.com
4
baidu
www.baidu.com
欢迎大家留言一起讨论学习!