避免SnakeYaml转储中的JavaBean Root标记

时间:2014-10-22 19:27:14

标签: java yaml dump snakeyaml

当我转储以下类的实例时:

class BrooklynApplicationEntity{
    private String id;
    private String location;
    private String name;
    List<BrooklynServiceEntity> services;

    //getters and setters
    ...
}

使用下一个代码:

 DumperOptions options = new DumperOptions();
 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
 options.setCanonical(false);
 options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
 SkipEmptyAndNullRepresenter skipEmptyAndNullRepresenter=
     new SkipEmptyAndNullRepresenter();

 Yaml yaml=new Yaml(skipEmptyAndNullRepresenter, options);
 yaml.dump(this.getBrooklynApplicationEntity(), file);

我获得了下一个yaml。

!!org.tomat.translate.brooklyn.entity.BrooklynApplicationEntity
id: dbApp
location: localhost
name: DatabaseApp
services:
- !!org.tomat.translate.brooklyn.entity.JBossBrooklynService
  brooklynConfigProperties:
    port.http: 80+
  id: JBossMainWebServer
  location: AWS
  name: JBoss Main Web Server
- !!org.tomat.translate.brooklyn.entity.JBossBrooklynService
  id: JBossSecondWebServer
  location: localhost
  name: JBoss

我想避免输出YAML中的TAG,所以我添加了下一条指令, 它在How to hide bean type in snakeyamlImplicitTagsTest中的描述。

    skipEmptyAndNullRepresenter.addClassTag(JBossAgnosticElement.class, Tag.MAP);
    skipEmptyAndNullRepresenter.addClassTag(JBossAgnosticElement.class, Tag.SEQ);

但是,TAG !!org.tomat.translate.brooklyn.entity.BrooklynApplicationEntity!!org.tomat.translate.brooklyn.entity.JBossBrooklynService不会被删除。

2 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。 当我向类添加隐式标记(例如TAG.Map)时,我必须使用完整的类名。 例如,为避免!!org.tomat.translate.brooklyn.entity.JBossAgnosticElement,必须使用下一条指令。

skipEmptyAndNullRepresenter.addClassTag(
    org.tomat.translate.brooklyn.entity.JBossAgnosticElement.class, Tag.MAP);

而不是

skipEmptyAndNullRepresenter.addClassTag(JBossAgnosticElement.class, Tag.MAP);

答案 1 :(得分:0)

 //write seperate function to remove tag comments !!sometest.Trades from the yaml file as it will cause issue while reading it
            Representer representer = new Representer() {
                @Override
                protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
                    // if value of property is null, ignore it.
                    if (int.class.equals(property.getType())) {
                        return null;
                    } else {
                        return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
                    }
                }
            };
            representer.addClassTag(sometest.Trades.class, Tag.MAP);
            Yaml yaml1 = new Yaml(representer, options);
 Writer output;
            output = new BufferedWriter(new FileWriter(outputFilePath, true));
            yaml1.dump(trades, output);
            output.close();