使用 Jackson 将 Java 对象实例写入 YAML [英] Writing Java object instance to YAML using Jackson

查看:34
本文介绍了使用 Jackson 将 Java 对象实例写入 YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例"Pojo 类,如下所述.任何人都可以使用 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;
}

}

推荐答案

Jackson 有一个 支持 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆