Skip to content

Java Bean To YAML

Mihai A edited this page Nov 29, 2022 · 9 revisions

Java Beans To YAML

You can parse a Java Bean to YAML ("dump" it) as follows:

final Map<String, Integer> grades = new HashMap<>();
grades.put("Math", 9);
grades.put("CS", 10);
final Student student = new Student("John", "Doe", 20, grades);
YamlMapping student = Yaml.createYamlDump(student).dumpMapping();

student.toString() will print:

firstName: John
lastName: Doe
age: 20
grades: 
  CS: 10
  Math: 9

The keys of the mapping are all the public, non-void and parameterless methods of the bean. If the name of the accesor method starts with the classic get prefix, we cut it out. If the dumped object is a Map, the keys are obviously the ones of the Map.

You can also dump sequences or scalars using dumpSequence() or dumpScalar() respectively. There is also method dump() which gives you a generic YamlNode.

Clone this wiki locally