使用 Groovy 3.0 的新 YamlBuilder 编写文字 YAML 字段

Write a literal YAML field using Groovy 3.0's new YamlBuilder

Groovy 3.0 有一个新的 YamlBuilder class,其工作方式与现有的 JsonBuilder class.

类似

我正在尝试解决是否可以使用 YamlBuilder 在 YAML 中生成文字字段,例如:

data: |
  this is
  a literal
  text value

我的第一个猜测是 Groovy 的多行字符串可以工作:

new YamlBuilder() {
  data: '''\
this is
a literal
text value'''
}

但这给了我:

data: "this is\na literal\ntext value\n"`

我在 YamlBuilder Javadoc 中没有看到任何有用的东西,mrhaki 的 example 也没有显示这个用例。

有谁知道if/how这可以做到吗?

在幕后 Groovy 的 YamlBuilder 正在使用 Jackson 的 JSON 到 YAML 转换器。

Jackson 的转换器确实支持文字块样式,但这需要启用。 YamlBuilder当前版本不支持设置选项

我复制了 YamlBuilder class 和相关的 YamlConverter class 所以我可以修改设置。

在YamlBuilder class中,我修改了这个方法:

public static String convertJsonToYaml(Reader jsonReader) {
    try (Reader reader = jsonReader) {
        JsonNode json = new ObjectMapper().readTree(reader);

        return new YAMLMapper().writeValueAsString(json);
    } catch (IOException e) {
        throw new YamlRuntimeException(e);
    }
}

变成这样:

public static String convertJsonToYaml(Reader jsonReader) {
    try (Reader reader = jsonReader) {
        JsonNode json = new ObjectMapper().readTree(reader);

        YAMLMapper mapper = new YAMLMapper()
        mapper.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true)
        return mapper.writeValueAsString(json);
    } catch (IOException e) {
        throw new YamlRuntimeException(e);
    }
}

这让我可以做到:

mapper.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true)

这将成功地将 YAML 呈现为文字块:

data: |-
  this is
  a literal
  text value

您可以执行以下操作:

import groovy.yaml.*
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import static com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature.LITERAL_BLOCK_STYLE

def yaml = new YamlBuilder()

yaml {
  data '''\
this is
a literal
text value'''
}

println new ObjectMapper(new YAMLFactory().configure(LITERAL_BLOCK_STYLE, true)).writeValueAsString(yaml)

如果您需要自己的自定义序列化