Jackson YAML 序列化 - 防止多行写入

Jackson YAML Serialization - Prevent Multiline Writing

我正在尝试从 beans 创建一个 YAML 文件。其中一个字段超过 80 个字符。当我使用 objectMapper 将 bean 写入 YAML 文件时,这些值打印在不同的两行中。

- code: abcd1234
  label-en_US: Lorem Ipsum is simply dummied text of the printing and typesetting
    industry --> this line should not be here
ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(MINIMIZE_QUOTES));

mapper.writeValue(Paths.get("path/to/file").toFile(), getData());

所以你不希望长文本被多行包裹,这应该让你思考 YAMLFactory 中是否有一个选项来控制它。

然后您检查 文档 ,即 YAMLFactory, to see if there is anything useful for that. Looking through the list of methods, you notice the disable(YAMLGenerator.Feature f) and enable(YAMLGenerator.Feature f) methods and you ponder if there is a YAMLGenerator.Feature 的 javadoc 以获得您想要的内容。

查看list of features, you find one called SPLIT_LINES,描述为:

Options passed to SnakeYAML that determines whether longer textual content gets automatically split into multiple lines or not.

Feature is enabled by default to conform to SnakeYAML defaults as well as backwards compatibility with 2.5 and earlier versions.

在你的 研究 技能的威力下跳了一小段胜利舞之后......好吧,不,你不要那样做,因为必须在这里领导表明缺乏有这样的技能,但你对自己惊叹不已,希望在未来提高自己的研究技能......你将 disable(SPLIT_LINES) 添加到代码中。

YAMLFactory yamlFactory = YAMLFactory.builder()
        .enable(MINIMIZE_QUOTES)
        .disable(SPLIT_LINES)
        .build();
ObjectMapper mapper = new ObjectMapper(yamlFactory);