将多行字符串从 JsonNode 序列化为 YAML 字符串添加双引号和“\n”

Serializing multiline string from JsonNode to YAML string adds double quotes and "\n"

我有一个 YAML 字符串,其中一个属性如下所示:

 description: |
    this is my description  //imagine there's a space after description
    this is my description in the second line

在我的 Java 代码中,我将其读入 JsonNode,如下所示:

JsonNode node = new YamlMapper().readTree(yamlString);

然后我对其进行一些更改并将其写回这样的字符串:

new YamlMapper().writeValueAsString(node))

新字符串现在看起来像这样:

"this is my description \nthis is my description in the second line\n"

所以现在在 YAML 文件中你可以看到添加的引号 + 换行符 (\n) 并且所有内容都在一行中。我希望它 return 像上面那个那样的原始 YAML。

这是我的 YAML 对象映射器的配置方式:

 new ObjectMapper(
        new YAMLFactory()
          .disable(YAMLGenerator.Feature.MINIMIZE_QUOTES))
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

如果我删除原始 YAML 中 description 之后的 space,它就可以正常工作

Jackson的API级别太高,无法详细控制输出。您可以直接使用 SnakeYAML(Jackson 在后台使用它),但您需要下到 API 的节点或事件级别来控制输出中的节点样式。

另请参阅:

This answer shows general usage of SnakeYAML's event API to keep formatting; of course it's harder to do changes on a stream of events. You might instead want to work on the node graph, this answer 有一些示例代码展示了如何将 YAML 加载到节点图、处理它并再次写回。

使用 jackson 序列化多行文本。 Jackson从2.9版本开始引入了一个新的flag YAMLGenerator.Feature.LITERAL_BLOCK_STYLE,可以开启为:

new ObjectMapper(
    new YAMLFactory().enable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE)
).writeValueAsString(new HashMap<String, String>(){{
    put("key", "test1\ntest2\ntest3");
}});

输出不会用引号引起来:

---
key: |-
  test1
  test2
  test3

请注意 “块标量” 之间存在一些差异:||->。 ..,您可以在 https://yaml-multiline.info/

查看