YAML,YAML Ain’t Markup Language的简称。是一种人性化、跨语言的数据序列化标准,基于Unicode的数据序列化语言,围绕敏捷编程语言的常见本地数据类型而设计。它广泛地用于编程需求,从配置文件到Internet消息传递、对象持久性到数据审计。
YAML文件可以由单个或多个文档组成(文档之间相互独立)。多个文档之间使用“—”(三个横线)作为文档的开始分隔符。使用“…”(三个点)作为文档的结束分隔符(可省略)。单个文档省略分隔符。
# 整数
age: 10
# 浮点
price: 1.48
# 字符串
name: Jane
address: BeiJing
# 布尔
online: true
# Null
car: ~
# 时间(ISO8601 格式)
time: 2019-02-28t21:59:43.10-05:00
# 日期(iso8601 格式的年、月、日)
date: 2019-02-28
# 对象,即person:{name:Jane, age:20, address:BeiJing}
person:
name: Jane
age: 20
address: BeiJing
# 数组,即pets:[cat, dog, pig]
pets:
- cat
- dog
- pig
planetName: Earth
continents:
- name: Asia
countries:
- China
- Japan
- Korea
- name: Europe
countries:
- England
- France
- Germany
- name: North America
countries:
- Ameriac
- Canada
- Mexico
- name: South America
countries:
- Brazil
- Argentina
- Chile
- name: Oceania
countries:
- Australia
- New Zealand
- name: Africa
countries:
- Egypt
- zimbabwe
- name: Antarctica
@Data
public class Earth {
private String planetName;
private List continents;
}
@Data
public class Continent {
private String name;
private List countries;
}
<dependency>
<groupId>org.yamlgroupId>
<artifactId>snakeyamlartifactId>
<version>1.23version>
dependency>
public class SnakeYaml {
public static void main(String[] args) {
// yml文件转Java对象
Yaml yaml = new Yaml();
InputStream input = SnakeYaml.class.getResourceAsStream("/earth.yml");
Earth earth = yaml.loadAs(input, Earth.class);
System.out.println(JSON.toJSONString(earth));
}
}
<dependency>
<groupId>org.jyamlgroupId>
<artifactId>jyamlartifactId>
<version>1.3version>
dependency>
public class JYaml {
public static void main(String[] args) throws FileNotFoundException {
// yml文件转Java对象
InputStream input = SnakeYaml.class.getResourceAsStream("/earth.yml");
Earth earth = Yaml.loadType(input, Earth.class);
System.out.println(JSON.toJSONString(earth));
}
}
<dependency>
<groupId>com.esotericsoftware.yamlbeansgroupId>
<artifactId>yamlbeansartifactId>
<version>1.13version>
dependency>
public class YamlBeans {
public static void main(String[] args) throws Exception {
// yml文件转Java对象
FileReader fileReader = new FileReader(new File(YamlBeans.class.getResource("/earth.yml").getPath()));
YamlReader reader = new YamlReader(fileReader);
Earth earth = reader.read(Earth.class);
System.out.println(JSON.toJSONString(earth));
// Java对象转yml文件
YamlWriter writer = new YamlWriter(new FileWriter("/Users/liuxiangxiang/Desktop/output.yml"));
writer.write(earth);
writer.close();
}
}