Skip to content

Java Bean To YAML

Mihai A edited this page Jan 19, 2024 · 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.

Pay attention: The order of the elements in the printed YAML will NOT necessarily follow the order in which the methods of the Java Bean are declared. Even if your first method is getFirstName(), the printed YAML might start with age or something else. This is because we use the JDK's reflection library and the provided getDeclaredMethods() method does NOT guarantee any order of the returned methods. This cannot be changed, unfortunately.

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

Java Beans to YAML with Comments

We offer the @YamlComment("...") annotation, which should be placed only on the accessor methods (not on the fields) of the Java Bean which you want to convert to YAML. Take the following Java Bean:

class Student {

   //private attributes

   @YamlComment("First name of the student.")
   public String getFirstName() {
      return this.firstName;
   }

   @YamlComment("Classes the student is enrolled to.")
   public List<String> getClasses() {
     return this.classes;
   }

   @YamlComment("Some grades of the student.")
   public Map<String, Integer> getGrades() {
     return this.grades;
   }
   //...
}
YamlMapping student = Yaml.createYamlDump(student).dump("Information about a student.");
//you can also add comment to the YAML Document as a whole, with the dump(String) method

This will print:

# Information about a student.
---
# First name of the student.
firstName: Mihai
lastName: Test
age: 20
gpa: 3.5
# Classes the student is enrolled to.
classes:
  - Math
  - CS
# Some grades of the student.
grades:
  Math: 9
  CS: 10