使用 Jackson 将 Java 对象实例写入 YAML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46445834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:13:12  来源:igfitidea点击:

Writing Java object instance to YAML using Hymanson

javaHymansonyamlHymanson2Hymanson-modules

提问by Ganesh Rao B

I have a 'Example' Pojo class as mentioned below. Can any one tel to save instance of Example class to YAML file using Hymanson.

我有一个“示例”Pojo 类,如下所述。任何人都可以使用 Hymanson 将 Example 类的实例保存到 YAML 文件中。

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

}

}

回答by cassiomolin

Hymanson has a module that supports YAML. Ensure that you add the required dependencyto your project, then you can use it as following:

Hymanson 有一个支持 YAML模块。确保您将所需的依赖项添加到您的项目中,然后您可以按如下方式使用它:

// 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);