gpt4 book ai didi

java - Jackson YAML 序列化对象数组格式

转载 作者:行者123 更新时间:2023-11-30 10:10:33 24 4
gpt4 key购买 nike

我正在尝试以某种方式格式化我的 Jackson Yaml 序列化。

employees:
- name: John
age: 26
- name: Bill
age: 17

但是,当我序列化对象时,这是我得到的格式。

employees:
-
name: John
age: 26
-
name: Bill
age: 17

有什么方法可以去掉数组中对象开头的换行符吗?这纯粹是个人喜好/人类可读性问题。

这些是我当前在 YAMLFactory 上设置的属性:

YAMLFactory yamlFactory = new YAMLFactory()
.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) //removes quotes from strings
.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)//gets rid of -- at the start of the file.
.enable(YAMLGenerator.Feature.INDENT_ARRAYS);// enables indentation.

我查看了 Jackson 中 YAMLGenerator 的 Java 文档,并查看了关于 stackoverflow 的其他问题,但我找不到一个选项来做我想做的事情。

我已经尝试了 CANONICAL_OUTPUT、SPLIT_LINES 和 LITERAL_BLOCK_STYLE 属性,最后一个是在设置 MINIMIZE_QUOTES 时自动设置的。CANONICAL_OUTPUT 似乎在数组周围添加了括号。SPLIT_LINES 和 LITERAL_BLOCK_STYLE 与多行字符串的处理方式有关。

最佳答案

简短的回答是目前没有办法通过 Jackson 做到这一点。这是由于 snakeyaml 中的一个错误,如果您设置 indicatorIndent 属性,则不会正确处理空格,因此 snakeyaml 会添加新行。

我找到了直接使用 snakeyaml 的解决方法。

//The representer allows us to ignore null properties, and to leave off the class definitions
Representer representer = new Representer() {
//ignore null properties
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
// if value of property is null, ignore it.
if (propertyValue == null) {
return null;
}
else {
return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}

//Don't print the class definition
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
if (!classTags.containsKey(javaBean.getClass())){
addClassTag(javaBean.getClass(), Tag.MAP);
}

return super.representJavaBean(properties, javaBean);
}
};



DumperOptions dumperOptions = new DumperOptions();
//prints the yaml as nested blocks
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
//indicatorIndent indents the '-' character for lists
dumperOptions.setIndicatorIndent(2);
//This is the workaround. Indent must be set to at least 2 higher than the indicator indent because of how whitespace is handled.
//If not set to 2 higher, then the newline is added.
dumperOptions.setIndent(4);
Yaml yaml = new Yaml(representer, dumperOptions);
//prints the object to a yaml string.
yaml.dump(object);

解决方法是在 DumperOptions 上设置缩进属性。您需要将缩进设置为至少比 indicatorIndent 高 2 的值,否则将添加换行符。这是由于在 snakeyaml 中处理空格的方式。

关于java - Jackson YAML 序列化对象数组格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52784112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com