8

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);
}
Laa
  • 393
  • 2
  • 7

3 Answers3

20

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

Representer representer = new Representer();
representer.addClassTag(Person.class, Tag.MAP);
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73
Laa
  • 393
  • 2
  • 7
9

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

}
edgraaff
  • 481
  • 4
  • 5
1

Some more clarity on using org.yaml.snakeyaml.representer.Representer, it needs to be passed to YAML:

DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);

Representer representer = new Representer(options);
representer.addClassTag(Person.class, Tag.MAP); // Put your class here

Yaml yaml = new Yaml(representer, options);
String output = yaml.dump(person); // Put your object here
System.out.println(output);
Craigo
  • 3,384
  • 30
  • 22