【问题标题】:How to hide bean type in snakeyaml如何在snakeyaml中隐藏bean类型
【发布时间】:2013-10-15 06:39:06
【问题描述】:

此代码将输出:(YAML)

--- !!org.test.bean.Person

地址:4011 16th Ave S

.....

无论如何都可以隐藏我的 bean 类型(org.test.bean.Person)!? (更喜欢使用snakeyaml配置...我找不到它..)

谢谢!!

public static void dumpYAML(){
    Constructor constructor = new Constructor(Person.class);
    TypeDescription personDescription = new TypeDescription(Person.class);
    personDescription.putListPropertyType("phone", Tel.class);
    constructor.addTypeDescription(personDescription);

    Yaml yaml = new Yaml(constructor);
    Person person = (Person) yaml.load(makeYAML());

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setCanonical(false); // display bean member attribute
    options.setExplicitStart(true); // display --- start

    yaml = new Yaml(options);
    String output = yaml.dump(person);
    System.out.println(output);
}

【问题讨论】:

    标签: java yaml snakeyaml


    【解决方案1】:

    使用org.yaml.snakeyaml.representer.Representer,设置Tag.MAP隐藏根标签。

    Representer representer = new Representer();
    representer.addClassTag(Person.class, Tag.MAP);
    

    【讨论】:

      【解决方案2】:

      您可以扩展 Representer 以“偷偷地”注入任何未注册的 bean 类作为 Map。

      public class MapRepresenter extends Representer {
      
          @Override
          protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
              if (!classTags.containsKey(javaBean.getClass()))
                  addClassTag(javaBean.getClass(), Tag.MAP);
      
              return super.representJavaBean(properties, javaBean);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-26
        • 2017-04-04
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 2011-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多