1

Groovy 3.0 有一个新的 YamlBuilder 类,其工作方式与现有的 JsonBuilder 类类似。

我正在尝试确定是否可以使用 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 的示例也没有显示这个用例。

有谁知道是否/如何做到这一点?

4

2 回答 2

3

您可以执行以下操作:

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)

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

于 2020-02-25T10:13:51.970 回答
2

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

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

我复制了 YamlBuilder 类和相关的 YamlConverter 类,以便修改设置。

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

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
于 2020-02-25T10:10:15.133 回答