简体   繁体   English

如何在YAML中将Java字符串解析为文字块

[英]How to parse a Java String as a literal block in YAML

I need to parse only the Java Strings description , instructions as literal blocks ( | ) in yaml,as both the above variables can contain multiline inputs and parse infoId as a usual string. 我只需要将Java Strings descriptioninstructions解析为yaml中的文字块( | ),因为上述两个变量都可以包含多行输入,并且可以将infoId解析为常规字符串。 I am using snakeyaml as the yaml library. 我正在使用snakeyaml作为yaml库。 How do I achieve the above? 如何实现以上目标? Is there any annotation that I need use for this? 我需要为此使用任何注释吗?

Pojo class Pojo课

public class Info {

private String infoId;
private String description;
private String instructions;

// Setters and getters
}

parsing class 解析类

...
Info info = new Info();
info.setDescription(descriptionWithMultilines);
info.setIntructions(instructionsWithMultilines);

Yaml yaml = new Yaml();
String yamlString = yaml.dumpAs(info, Tag.MAP, DumperOptions.FlowStyle.BLOCK);
...

If you want to exclude specific properties you can achieve it by using a custom Representer class 如果要排除特定属性,则可以使用自定义Representer类来实现

this short snippet 这个简短的片段

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);
        }
    }
}

produces following output 产生以下输出

description: |-
  foo
  bar
instructions: |-
  one
  two

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM