一、引入依賴
<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.18</version>
</dependency>
二、定義對象
import java.util.List;
import java.util.Map;
public class Model {
private Integer age;
private String name;
private Map<String, Object> params;
private List<String> favoriteBooks;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
public List<String> getFavoriteBooks() {
return favoriteBooks;
}
public void setFavoriteBooks(List<String> favoriteBooks) {
this.favoriteBooks = favoriteBooks;
}
}
三、輸出yaml
@Test
public void testDumpFile() throws IOException {
Model model = new Model();
model.setAge(12);
model.setName("張三");
List<String> list = Arrays.asList(new String[] { "aa", "bb" });
model.setFavoriteBooks(list);
Map<String, Object> params = new HashMap<>();
params.put("cc", "dd");
params.put("ee", "ff");
params.put("gg", "hh");
model.setParams(params);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
FileWriter fw = new FileWriter(new File("d:/1.yml"));
yaml.dump(model, fw);
}
四、解析yaml
@Test
public void testParseYaml() throws FileNotFoundException {
Yaml yaml = new Yaml();
File file = new File("d:/1.yml");
Model model = yaml.loadAs(new FileInputStream(file), Model.class);
System.out.println(JSON.toJSONString(model));
}