How to hide bean type in snakeyaml

时光毁灭记忆、已成空白 提交于 2019-12-22 06:56:07

问题


This code will output:(YAML)

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

address: 4011 16th Ave S

.....

Can hide my bean type(org.test.bean.Person) anyway !? (prefer to use snakeyaml config...i can't find it..)

thanks!!

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

回答1:


Use org.yaml.snakeyaml.representer.Representer, set Tag.MAP can hide root tag.

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



回答2:


You can extend Representer to 'sneakily' inject any non-registered bean class as 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);
    }

}


来源:https://stackoverflow.com/questions/19246027/how-to-hide-bean-type-in-snakeyaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!