Json文件
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"); //构建JSONArray数组
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");//构建JSONArray数组
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()
获取。
读取yaml文件
1. 导入依赖
<dependencies>
<dependency>
<groupId>org.jyaml</groupId>
<artifactId>jyaml</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.28</version>
</dependency>
</dependencies>
2. yaml文件
ip: "127.0.0.1"
port: "8000"
---
ip: "127.0.0.2"
port: "9000"
---
ip: "127.0.0.3"
port: "10000"
3. 读取文件
public static void readY() throws FileNotFoundException {
Yaml yaml = new Yaml();
File f = new File("/home/user/project/test.yml");
Iterable<Object> result = yaml.loadAll(new FileInputStream(f));
for (Object obj : result) {
LinkedHashMap<String,String> msg = (LinkedHashMap) obj;
System.out.println(msg.get("ip") + msg.get("port"));
}
}