2013-10-08 67 views
3

此代碼Bean類型將輸出:(YAML)如何隱藏在snakeyaml

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

地址:4011第16大道小號

.. ...

無論如何都可以隱藏我的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); 
} 

回答

6

使用org.yaml.snakeyaml.representer.Representer,設置Tag.MAP可以隱藏根標籤。

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

您可以擴展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); 
    } 

}