Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Java 使用 SnakeYAML 解析 YAML 文件

Java YAML 大约 1302 字

介绍

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

阅读 973 · 发布于 2022-06-04

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

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

扫描二维码关注我
昵称:
随便看看 换一批