Maven Dependency
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.14</version>
</dependency>
String → Map
Data
data1: AAA
data2:
- aaa
- bbb
- ccc
data3:
zzz: ZZZ
yyy: YYY
xxx: XXX
Code
Yaml sYaml = new Yaml();
@SuppressWarnings("unchecked")
Map<String, Object> yaml = (Map<String, Object>) sYaml.load(yamlString);
assertThat((String) yaml.get("data1"), is("AAA"));
@SuppressWarnings("unchecked")
List<String> data2 = (List<String>) yaml.get("data2");
assertThat(data2.get(0), is("aaa"));
assertThat(data2.get(1), is("bbb"));
assertThat(data2.get(2), is("ccc"));
@SuppressWarnings("unchecked")
Map<String, String> data3 = (Map<String, String>) yaml.get("data3");
assertThat(data3.get("zzz"), is("ZZZ"));
assertThat(data3.get("yyy"), is("YYY"));
assertThat(data3.get("xxx"), is("XXX"));
String → Bean
Data
!!com.YamlBean
data1: AAA
data2:
- aaa
- bbb
- ccc
data3:
zzz: ZZZ
yyy: YYY
xxx: XXX
Bean
YamlBean.java
package com;
import java.util.List;
import java.util.Map;
public class YamlBean {
private String data1;
private List<String> data2;
private Map<String, String> data3;
public String getData1() {
return data1;
}
public void setData1(String data1) {
this.data1 = data1;
}
public List<String> getData2() {
return data2;
}
public void setData2(List<String> data2) {
this.data2 = data2;
}
public Map<String, String> getData3() {
return data3;
}
public void setData3(Map<String, String> data3) {
this.data3 = data3;
}
}
Code1
Yaml yaml = new Yaml();
YamlBean yamlBean = (YamlBean) yaml.load(yamlString);
assertThat(yamlBean.getData1(), is("AAA"));
assertThat(yamlBean.getData2().get(0), is("aaa"));
assertThat(yamlBean.getData2().get(1), is("bbb"));
assertThat(yamlBean.getData2().get(2), is("ccc"));
assertThat(yamlBean.getData3().get("zzz"), is("ZZZ"));
assertThat(yamlBean.getData3().get("yyy"), is("YYY"));
assertThat(yamlBean.getData3().get("xxx"), is("XXX"));
Code2
こちらの書き方でも動作すると思っているのですが、
loadAsメソッドでNoSuchMethodErrorが発生しているので未確認。。。
Yaml yaml = new Yaml();
YamlBean yamlBean = yaml.loadAs(yamlString, YamlBean.class);
assertThat(yamlBean.getData1(), is("AAA"));
assertThat(yamlBean.getData2().get(0), is("aaa"));
assertThat(yamlBean.getData2().get(1), is("bbb"));
assertThat(yamlBean.getData2().get(2), is("ccc"));
assertThat(yamlBean.getData3().get("zzz"), is("ZZZ"));
assertThat(yamlBean.getData3().get("yyy"), is("YYY"));
assertThat(yamlBean.getData3().get("xxx"), is("XXX"));