Close

How to convert Java Objects to YAML format in SnakeYAML?

[Last Updated: Jul 31, 2017]

In this example, we will learn how to convert Java Objects to YAML data in SnakeYAML.

Dumping Java Object to YAML String

public class JavaToYamlExample {

  public static void main(String[] args) {
      Map<String, Map<String, String>> map = createMap();
      Yaml yaml = new Yaml();
      String output = yaml.dump(map);
      System.out.println(output);
  }

  private static Map<String, Map<String, String>> createMap() {
      Map<String, Map<String, String>> map = new HashMap<>();
      for (int i = 1; i <= 3; i++) {
          Map<String, String> map2 = new HashMap<>();
          map2.put("key1" + i, "value1" + i);
          map2.put("key2" + i, "value2" + i);
          map2.put("key3" + i, "value4" + i);
          map.put("key" + i, map2);
      }
      return map;
  }
}

Output

key1: {key11: value11, key21: value21, key31: value41}
key2: {key12: value12, key22: value22, key32: value42}
key3: {key13: value13, key23: value23, key33: value43}

We can also use the overloaded method Yaml#dump(Object data, Writer output) to serialized Yaml to files.

Dumping with Options

We can customize the output as shown in this example:

public class JavaToYamlWithOptions {

  public static void main(String[] args) {
      Map<String, Map<String, String>> map = createMap();

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

      Yaml yaml = new Yaml(options);
      String output = yaml.dump(map);
      System.out.println(output);
  }

  private static Map<String, Map<String, String>> createMap() {
      Map<String, Map<String, String>> map = new HashMap<>();
      for (int i = 1; i <= 3; i++) {
          Map<String, String> map2 = new HashMap<>();
          map2.put("key1" + i, "value1" + i);
          map2.put("key2" + i, "value2" + i);
          map2.put("key3" + i, "value4" + i);
          map.put("key" + i, map2);
      }
      return map;
  }
}

Output

key1:
key11: value11
key21: value21
key31: value41
key2:
key12: value12
key22: value22
key32: value42
key3:
key13: value13
key23: value23
key33: value43

Converting Java Objects to Yaml format can also be very useful if we want to learn Yaml syntax quickly. This way we can avoid going through trial and error steps when writing Yaml with complex structure.

Example Project

Dependencies and Technologies Used:

  • snakeyaml 1.18: YAML 1.1 parser and emitter for Java.
  • JDK 1.8
  • Maven 3.3.9

Snakeyaml Java To Yaml Examples Select All Download
  • java-object-to-yaml-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • JavaToYamlWithOptions.java

    See Also