将多行字符串从 JsonNode 序列化为 YAML 字符串添加双引号和“\n" [英] Serializing multiline string from JsonNode to YAML string adds double quotes and "\n"

查看:24
本文介绍了将多行字符串从 JsonNode 序列化为 YAML 字符串添加双引号和“\n"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a YAML string where one of the attributes looks like this:

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

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

In my Java code I read it into a JsonNode like this:

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

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

I then do some changes to it and write it back to a string like this:

new YamlMapper().writeValueAsString(node))

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

The new string now looks like this:

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

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

So now in the YAML file you can see the added quotes + the new line character (\n) and everything is in one line. I expect it to return the original YAML like the one above.

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

This is how my YAML object mapper is configured:

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

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

If I remove the space after description in the original YAML, it works just fine

推荐答案

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

Jackson's API is too high level to control the output in detail. You can use SnakeYAML directly (which is used by Jackson under the hood), but you need to go down to the node or event level of the API to control node style in the output.

另见:我想加载一个 YAML 文件,可能编辑数据,然后再次转储.如何保留格式?

这个答案 展示了 SnakeYAML 事件 API 的一般用法以保持格式;当然,对一系列事件进行更改更难.您可能想要处理节点图,这个答案 有一些示例代码显示了如何将 YAML 加载到节点图,处理它,然后再写回来.

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 has some example code showing how to load YAML to a node graph, process it, and write it back again.

这篇关于将多行字符串从 JsonNode 序列化为 YAML 字符串添加双引号和“\n"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆