输出和读取yaml

本文详细介绍了如何在Java项目中使用SnakeYAML库进行YAML文件的读写操作。首先,展示了如何引入SnakeYAML的依赖;接着,定义了一个用于映射YAML数据的对象模型;然后,演示了如何将对象转换为YAML格式并写入文件;最后,介绍了如何从YAML文件中解析数据并转换为Java对象。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值