[英]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.