使用Jackson将Java对象实例编写到YAML [英] Writing Java object instance to YAML using Jackson
本文介绍了使用Jackson将Java对象实例编写到YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个'示例'Pojo类,如下所述。
任何一个tel都可以使用Jackson将Example类的实例保存到YAML文件。
I have a 'Example' Pojo class as mentioned below. Can any one tel to save instance of Example class to YAML file using Jackson.
public class Example {
String name;
int value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
推荐答案
杰克逊有一个支持YAML的模块。确保将所需的依赖关系添加到您的项目,然后你可以使用如下:
Jackson has a module that supports YAML. Ensure that you add the required dependency to your project, then you can use it as following:
// Create an ObjectMapper mapper for YAML
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
// Write object as YAML file
mapper.writeValue(new File("/path/to/yaml/file"), example);
或者你可以把你的对象写成一个字符串:
Alternatively you can write your object as a string:
// Write object as YAML string
String yaml = mapper.writeValueAsString(example);
这篇关于使用Jackson将Java对象实例编写到YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文