1. 导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
2. 准备JSON文件
{
"name": "张三他爹",
"age": "50",
"sons": [
{
"name": "zs",
"age": "20",
"sex": "man"
},
{
"name": "lisi",
"age": "21",
"sex": "man"
},
{
"name": "wangwu",
"age": "22",
"sex": "woman"
}
]
}
3. 读取Json文件
1. 读取文件
public static String readFile(String path) {
StringBuffer sb = new StringBuffer();
try {
Reader reader = new InputStreamReader(new FileInputStream(path));
int ch = 0;
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
2. 解析Json对象
public static void main(String[] args) throws IOException {
String s = readJsonFile("/home/myuser/Documents/a.json");
JSONObject jsonObject = JSON.parseObject(s);
JSONArray sons = jsonObject.getJSONArray("sons");
sons.stream().forEach(son -> {
System.out.println(son.toString());
});
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("age"));
}
结果如下所示:
{"sex":"man","name":"zs","age":"20"}
{"sex":"man","name":"lisi","age":"21"}
{"sex":"woman","name":"wangwu","age":"22"}
张三他爹
50
3. 实体类 存在实体类 Son 的时候,可以直接将Json对象解析为实体类对象。 必须有Setter方法
public class Son {
private String name;
private int age;
private String sex;
}
public static void main(String[] args) {
String s = readJsonFile("/home/wenfengz/Documents/a.json");
JSONObject jsonObject = JSON.parseObject(s);
JSONArray sons = jsonObject.getJSONArray("sons");
for (int i = 0; i < sons.size(); i++) {
Son son = sons.getObject(i, Son.class);
System.out.println(son);
}
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("age"));
}
4. 注意事项 JSON 文件中:
-
用 [ ] 包起来代表数组,要用 JSONArray 解析 。 -
用 { } 包起来的表示对象, 用JSONObject 解析获取。 -
最外层如果是 [ ] 则用 JSON.parseArray() 获取。
|