[英]Write a literal YAML field using Groovy 3.0's new YamlBuilder
Groovy 3.0 has a new YamlBuilder class that works in a similar way to the existing JsonBuilder class. Groovy 3.0 有一个新的 YamlBuilder 类,它的工作方式与现有的 JsonBuilder 类类似。
I'm trying to work out if I can use YamlBuilder to generate a literal field in YAML such as:我正在尝试确定是否可以使用 YamlBuilder 在 YAML 中生成文字字段,例如:
data: |
this is
a literal
text value
My first guess was Groovy's multiline string would work:我的第一个猜测是 Groovy 的多行字符串会起作用:
new YamlBuilder() {
data: '''\
this is
a literal
text value'''
}
But that gives me:但这给了我:
data: "this is\na literal\ntext value\n"`
I don't see anything useful in the YamlBuilder Javadoc and mrhaki's example doesn't show this use-case.我在 YamlBuilder Javadoc 中没有看到任何有用的东西,并且 mrhaki 的示例没有显示这个用例。
Does anyone know if/how this can be done?有谁知道是否/如何做到这一点?
You can do the following:您可以执行以下操作:
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)
If you need your own custom serialization如果您需要自己的自定义序列化
Under the covers Groovy's YamlBuilder is using Jackson's JSON to YAML converter.在幕后,Groovy 的 YamlBuilder 正在使用 Jackson 的 JSON 到 YAML 转换器。
Jackson's converter does support literal block style, but this needs to be enabled. Jackson 的转换器确实支持文字块样式,但这需要启用。 The current version of YamlBuilder does not support setting options.
当前版本的 YamlBuilder 不支持设置选项。
I copied the YamlBuilder class and the related YamlConverter class so I could modify the settings.我复制了 YamlBuilder 类和相关的 YamlConverter 类,以便我可以修改设置。
In the YamlBuilder class, I modified this method:在 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);
}
}
To be this:要这样:
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);
}
}
This allows me to do:这让我可以这样做:
mapper.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true)
Which will successfully render the YAML as a literal block:这将成功将 YAML 呈现为文字块:
data: |-
this is
a literal
text value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.