我只需要将Java字符串description
,instructions
解析为yaml中的文字块(|
),因为上述两个变量都可以包含多行输入并可以解析{{1} }作为常规字符串。我正在使用infoId
作为yaml库。如何实现以上目标?我需要为此使用任何注释吗?
Pojo类
snakeyaml
解析类
public class Info {
private String infoId;
private String description;
private String instructions;
// Setters and getters
}
答案 0 :(得分:0)
如果要排除特定属性,则可以使用自定义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