输出和读取yaml

2023-11-13

1、引入依赖

<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.18</version>
</dependency>

2、定义对象

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;
	}
}

3、输出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);
}

4、解析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));
}

5、官方文档

snakeyaml / snakeyaml / wiki / Documentation — Bitbucket

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

输出和读取yaml 的相关文章

随机推荐