YAML学习笔记

一、YAML简介

YAML,即YAML Ain’t Markup Language的缩写,YAML 是一种简洁的非标记语言。YAML以数据为中心,使用空白,缩进,分行组织数据,从而使得表示更加简洁易读。

二、YAML语法

1、基本规则

YAML有以下基本规则:

  1. 大小写敏感


  1. 使用缩进表示层级关系
  2. 禁止使用tab缩进,只能使用空格键
  3. 缩进长度没有限制,只要元素对齐就表示这些元素属于一个层级。
  4. 使用#表示注释

  1. 字符串可以不用引号标注


2、数据类型

  1. 字符串
#YAML
str: abc
#JSON
{
str:'abc'
}
#YAML
#包含特殊字符需要加引号
str: '内容:字符串'
#JSON
{
str:'内容:字符串'
}
#YAML
#单双引号均可,双引号不会对特殊符号转义
s1: '内容\n字符串'
s2: "内容\n字符串"
#JSON
{
s1:'内容\\n字符串',
s2:'内容\n字符串'
}
  1. 布尔值
    布尔值用​​​true​​​和​​false​​表示
#YAML
isTrue: true
isTrue: false
#JSON
{
isTrue:true,
isTrue:false
}
  1. 整数
    数值直接以字面形式表示
#YAML
int: 10
#JSON
{
int:10
}
  1. 浮点数
    数值直接以字面形式表示
float: 1.23
double: 2.34
#JSON
{
float:1.23,
double:2.34
}
  1. Null
    ​​​null​​​值用​​~​​表示
#YAML
person: ~
{
person:null
}
  1. 时间
    时间采用ISO8601格式表示
#YAML
iso8601: 2018-05-20t10:59:43.10-05:00
#JSON
{
iso8601:new Date('2018-05-20t10:59:43.10-05:00')
}
  1. 日期
    日期采用ISO8601的格式yyyy-MM-dd表示
#YAML
date: 2018-05-20
{
date:new Date('2018-05-20')
}

注:YAML允许使用两个感叹号强制转换类型

#YAML
str1: !!str 123
str2: !!str true
#JSON
{
str1:'123',
str2:'true'
}


3、数据结构

1. Map,散列表
使用​​​:​​表示键值对,统一缩进的所有键值对属于一个Map

name: John
age: 18
#也可以写在一行
{ name: John, age: 18}
#JSON
{
'name':'John',
'age': 18
}

2、List,数组
使用​​​-​​来表示数组中的一个元素

#YAML
- a
- b
- c
#也可以写在一行
[a, b, c]
#JSON
['a', 'b', 'c']

3、scalar,纯量
数据的最小单位,不可再分割

4、数据结构的嵌套

YAML中的数据结构可以相互嵌套,嵌套方式有如下几种:
1、Map嵌套Map

#YAML
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org
#JSON
{ websites:
{ YAML: 'yaml.org',
Ruby: 'ruby-lang.org',
Python: 'python.org',
Perl: 'use.perl.org' } }

2、Map嵌套List

#YAML
languages:
- Ruby
- Perl
- Python
- c
#JSON
{
languages:[
'Ruby',
'Perl',
'Python',
'c']
}

3、List嵌套List

#YAML
-
- Ruby
- Perl
- Python
-
- c
- c++
- java
#或者
- [Ruby,Perl,Python]
- [c,c++,java]
#JSON
[
[
'Ruby',
'Perl',
'Python'
],
[
'c',
'c++',
'java'
]
]

4、List嵌套Map

#YAML
-
name: John
age: 18
-
name: Lucy
age: 16
#JSON
[
{
'name':'John',
'age':18
},
{
'name':'Lucy',
'age':16
}
]

三、Java对YAML文件的操作

1、SnakeYAML简介

SnakeYAML是一个完整的YAML1.1规范Processor,支持UTF-8/UTF-16,支持Java对象的序列化/反序列化,支持所有YAML定义的类型。

2、SnakeYAML依赖添加

在pom文件中加入依赖

<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.21</version>
</dependency>

3、SnakeYAML的使用方法

1. 建立Person类

import lombok.Data;//lombok为一种Java工具框架

@Data
public class Person {
private String name;
private Integer age;
}

2、建立person.yml文件

# person.yml
!!com.demo.Person {age: 24, name: Adam}

3、读取并解析YAML文件

  1. ​<T> T load(InputStream input)​
//获取YAML中的单个对象
@Test
public void testLoadYaml() throws FileNotFoundException {
Yaml yaml = new Yaml();
File ymlFile = new File(System.getProperty("user.dir") + "/src/main/resources/person.yml");
Person person = yaml.load(new FileInputStream(ymlFile));
System.out.println(person);
}

输出结果为:

Person(name=Adam, age=24)

//获取YAML中的单个对象
@Test
public void testLoadYaml2() throws FileNotFoundException {
Yaml yaml = new Yaml();
File ymlFile = new File(System.getProperty("user.dir") + "/src/main/resources/person.yml");
List<Person> personList = yaml.load(new FileInputStream(ymlFile));
System.out.println(personList);
}

输出结果为:

[Person(name=Adam, age=24), Person(name=Jack, age=24), Person(name=Steve, age=24)]

  1. ​<T> T loadAs(InputStream input, Class<T> type)​
//读取YAML文件并返回一个对应类的对象
@Test
public void testLoadYaml() throws FileNotFoundException {
Yaml yaml = new Yaml();
File ymlFile = new File(System.getProperty("user.dir") + "/src/main/resources/person.yml");
Person person = yaml.loadAs(new FileInputStream(ymlFile), Person.class);
System.out.println(person);
}

输出结果为:

Person(name=John, age=20)

  1. ​Iterable<Object> loadAll(InputStream input)​
//读取YAML文件并返回一个Iterable接口的子类
@Test
public void testLoadAllYaml() throws FileNotFoundException {
Yaml yaml = new Yaml();
File ymlFile = new File(System.getProperty("user.dir") + "/src/main/resources/person.yml");
Iterable<Object> people = yaml.loadAll(new FileInputStream(ymlFile));
for (Object person : people) {
System.out.println(person);
}
}

输出结果为:

[{name=John, age=20}, {name=Steven, age=30}, {name=Jenny, age=18}]

  1. ​void dump(Object data, Writer output)​
//将POJO写入YAML文件
@Test
public void testDumpYaml() throws IOException {
Yaml yaml = new Yaml();
File ymlFile = new File(System.getProperty("user.dir") + "/src/main/resources/person.yml");
Person person = new Person();
person.setName("Adam");
person.setAge(24);
yaml.dump(person, new FileWriter(ymlFile));
}

输出结果为:

!!com.liheng.demo.Person {age: 24, name: Adam}
注:dump方法会将YAML文件中的数据覆盖

  1. ​void dumpAll(Iterator<? extends Object> data, Writer output)​
//通过Iterator迭代器批量写入YAML文件
@Test
public void testDumpAllYaml() throws IOException {
Yaml yaml = new Yaml();
File ymlFile = new File(System.getProperty("user.dir") + "/src/main/resources/person.yml");
Iterable<Object> people = yaml.loadAll(new FileInputStream(ymlFile));
List<Person> personList = Lists.newArrayList();
for (Object person : people) {
LinkedHashMap map = (LinkedHashMap) person;
Person p = new Person();
p.setName((String) map.get("name"));
p.setAge((Integer) map.get("age"));
personList.add(p);
}
yaml.dumpAll(personList.iterator(), new FileWriter(ymlFile));
}

输出结果为:

!!com.liheng.demo.Person {age: 20, name: John}
--- !!com.liheng.demo.Person {age: 30, name: Steven}
--- !!com.liheng.demo.Person {age: 18, name: Jenny}