我正在使用Jackson将对象序列化为YAML(jackson-dataformat-yaml库)。
我想为标量值生成literal style输出(例如以下示例中的'description'),如
---
id: 4711
description: |
FooBar
HelloWorld
但我只设法生成这样的引用标量:
---
id: 4711
description: "FooBar\nHelloWorld"
我用来生成ObjectMapper的代码(现在)非常简单:
YAMLFactory f = new YAMLFactory();
f.enable(YAMLGenerator.Feature.SPLIT_LINES); // setting does not matter
ObjectMapper objectMapperYaml = new ObjectMapper(f);
String yaml = objectMapperYaml.writeValueAsString(someObject);
我猜有可能生成文字样式标量值,但我不知道如何。欢迎任何提示!
答案 0 :(得分:3)
如果您将自己使用SNAKEYaml,则需要设置相应的转储程序选项:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultScalarStyle(ScalarStyle.LITERAL);
可悲的是,它不能通过JacksonFeature在这里完成。
快速浏览一下来源然后显示要启用的功能是MINIMIZE_QUOTES
,您可以在YAMLGenerator#writeString
中找到他们的算法。
所以这里是全班:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
public class NewClass {
private int id;
private String description;
public static void main(String... a) throws JsonProcessingException {
YAMLFactory f = new YAMLFactory();
f.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
ObjectMapper objectMapperYaml = new ObjectMapper(f);
final NewClass someObject = new NewClass();
someObject.setId(4711);
someObject.setDescription("Hallo\nWorld!");
System.out.println(objectMapperYaml.writeValueAsString(someObject));
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
答案 1 :(得分:1)
我知道这是一个使用了一年的主题,但这是Google建议的顶部链接,需要更新。
Jackson自2.9版开始支持字面样式。不过,bug
中的尾随空格存在问题示例:
YAMLMapper mapper = new YAMLMapper();
mapper.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true);
Map map = new HashMap();
map.put("literal_ok", "some value\n wih\n multiple\n new lines\nin it");
map.put("can_not_use_literal", "can not\n use literal \b because of the trailing spaces");
System.out.println(mapper.writeValueAsString(map));