[英]How to parse a Java String as a literal block in YAML
我只需要将Java Strings description
和instructions
解析为yaml中的文字块( |
),因为上述两个变量都可以包含多行输入,并且可以将infoId
解析为常规字符串。 我正在使用snakeyaml
作为yaml库。 如何实现以上目标? 我需要为此使用任何注释吗?
Pojo课
public class Info {
private String infoId;
private String description;
private String instructions;
// Setters and getters
}
解析类
...
Info info = new Info();
info.setDescription(descriptionWithMultilines);
info.setIntructions(instructionsWithMultilines);
Yaml yaml = new Yaml();
String yamlString = yaml.dumpAs(info, Tag.MAP, DumperOptions.FlowStyle.BLOCK);
...
如果要排除特定属性,则可以使用自定义Representer类来实现
这个简短的片段
public static void main(String[] args) {
Info info = new Info();
info.setInfoId("demo");
info.setDescription("foo\nbar");
info.setInstructions("one\ntwo");
Yaml yaml = new Yaml(new InfoRepresenter());
String yamlString = yaml.dumpAs(info, Tag.MAP, DumperOptions.FlowStyle.BLOCK);
System.out.println(yamlString);
}
private static class InfoRepresenter extends Representer {
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
Tag customTag) {
if (javaBean instanceof Info && "infoId".equals(property.getName())) {
return null;
} else {
return super.representJavaBeanProperty(javaBean, property, propertyValue,
customTag);
}
}
}
产生以下输出
description: |-
foo
bar
instructions: |-
one
two
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.