该笔记将记录:在 Apache Groovy 中,常用 YAML 操作,以及相关问题处理方法;
SnakeYAML for Groovy 2.4.21
Parsing YAML with SnakeYAML | Baeldung
@Grab(group=’org.yaml’, module=’snakeyaml’, version=’1.33′)
import org.yaml.snakeyaml.Yaml
def yaml = new Yaml()
def inputStream = new FileInputStream(“example.yaml”)
def data = yaml.load(inputStream)
println(data.person.name)
println(data.person.age)
Loading Multiple Documents
public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() {
Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions()));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream(“yaml/customers.yaml”);
int count = 0;
for (Object object : yaml.loadAll(inputStream)) {
count++;
assertTrue(object instanceof Customer);
}
assertEquals(2,count);
}
YamlSlurper for Groovy 3.0
import groovy.yaml.YamlSlurper
def ys = new YamlSlurper()
def yaml = ys.parseText(yamlString)
assert ‘groovy’ == yaml.language
assert ‘required’ == yaml.sudo
assert ‘trusty’ == yaml.dist
assert [‘openjdk10’, ‘oraclejdk9’, ‘oraclejdk8’] == yaml.matrix.include.jdk
assert [‘unset _JAVA_OPTIONS’] == yaml.be[……]