SnakeYaml官网:http://www.snakeyaml.org/
引入依赖
Gradle
implementation 'org.yaml:snakeyaml:1.29'
Maven
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.29</version> </dependency>
使用示例
package com.e404.test import org.yaml.snakeyaml.DumperOptions import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.nodes.Tag import java.io.FileInputStream import java.io.FileOutputStream fun main() { // 反序列化 val stu: Student = FileInputStream("in.yml").use { Yaml().loadAs(it, Student::class.java) } println("stu.name: ${stu.name}") println("stu.age: ${stu.age}") // 序列化 FileOutputStream("out.yml").use { it.bufferedWriter().use { bw -> // 字符串 (使用dumpAs以移除bean标签) val str: String = Yaml().dumpAs(stu, Tag.MAP, DumperOptions.FlowStyle.BLOCK) bw.write(str) } } } /** * 必须要有无参的构造方法和每个参数的getter和setter * * (idea下setter可以用alt+insert快速生成) * * 否则会报错 */ class Student(var name: String = "", var age: Int = 0)