Load Yaml as Map

This example will show how to load a yaml file into a java Map. Yaml, which is similar to JSON, is a human friendly format that is an alternative to a flat property structure. Instant yaml is a helpful tool that allows you to format yaml online. The snippets below will use the yaml file which contains the various yaml library name and a brief description.

JvYaml : Java port of RbYaml
SnakeYAML : Java 5 / YAML 1.1
YamlBeans : To/from JavaBeans
JYaml : Original Java Implementation

Snake Yaml

In this snippet we will use SnakeYaml, a YAML parser and emitter for Java, to parse a yaml document into a Hashmap.

@Test
public void load_yml_as_map_snake() {

    String yamlAsString = "{JYaml: Original Java Implementation, "
            + "JvYaml: Java port of RbYaml, SnakeYAML: Java 5 / YAML 1.1, "
            + "YamlBeans: To/from JavaBeans}";

    Yaml yaml = new Yaml();

    @SuppressWarnings("unchecked")
    Map<String, String> yamlParsers = (Map<String, String>) yaml
            .load(yamlAsString);

    assertThat(yamlParsers.keySet(),
            hasItems("JYaml", "JvYaml", "YamlBeans", "SnakeYAML"));
}