【问题标题】:How to parse a Java String as a literal block in YAML如何将 Java 字符串解析为 YAML 中的文字块
【发布时间】:2019-06-09 02:52:34
【问题描述】:

我只需要将 Java 字符串 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);
...

【问题讨论】:

  • 您能否添加一个示例,您希望输出是什么样的。

标签: java parsing annotations yaml snakeyaml


【解决方案1】:

如果您想排除特定属性,可以使用自定义Representer 类来实现

这个简短的sn-p

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

【讨论】:

  • 感谢您的回答,但是,我还需要反序列化infoId。 (infoId 作为普通字符串,descriptioninstructions 作为文字块)。你能帮我解决这个问题吗?很抱歉没有明确提及上述问题。
  • @KasunSiyambalapitiya 接受您更新的问题above variables ('description', 'instruction') can contain multiline inputs and parse 'infoId' as a usual string 您发布的 sn-p 已经做到了这一点。因此,请更新您的问题并添加一个示例,其中包含三个变量的值以及您期望输出的格式。
猜你喜欢
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 2015-01-28
  • 1970-01-01
相关资源
最近更新 更多