Java 使用 SnakeYAML 解析 YAML 文件

Java YAML About 1,302 words

介绍

SnakeYAML是针对YAML 1.1Java解析器。

Maven 依赖

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

解析单个 YAML

使用load加载单个YAML

person:
  name: tom
  age: 18
  address:
    - addressA
    - addressB

teams:
  - id: 1
    name: team1
    createTs: 2022-01-01
  - id: 2
    name: team2
    createTs: 2022-02-02
Yaml yaml = new Yaml();

InputStream inputStream1 = Thread.currentThread().getContextClassLoader().getResourceAsStream("testA.yml");
Map map = yaml.load(inputStream1);

System.out.println(map);

解析组合 YAML

使用loadAll加载组合的YAML

person:
  name: tom
  age: 18
  address:
    - addressA
    - addressB

teams:
  - id: 1
    name: team1
    createTs: 2022-01-01
  - id: 2
    name: team2
    createTs: 2022-02-02

---

testField:
  name: aaa

test: xxx
Yaml yaml = new Yaml();

InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("testB.yml");
Iterable<Object> objects = yaml.loadAll(inputStream2);

for (Object object : objects) {
    System.out.println(object);
    System.out.println("--------------------------------------");
}

官方文档

https://bitbucket.org/snakeyaml/snakeyaml/wiki/Documentation

开源地址

https://bitbucket.org/snakeyaml/snakeyaml

Views: 4,075 · Posted: 2022-06-04

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh