Search code examples
javadictionaryyamlsnakeyaml

SnakeYaml get stacked keys


When this is my .yml file:

test1: "string1"
test2:
  test3: "string2"

How do I get the value of test3?

Map<String, Object> yamlFile = new Yaml().load(YamlFileInputStream);

yamlFile.get("test1"); // output: string1
yamlFile.get("test2"); // output: {test3=string2}

yamlFile.get("test2.test3"); // output: key not found

Solution

  • YAML does not have „stacked keys“. It has nested mappings. The dot . is not a special character and can occur normally in a key, therefore you cannot use it for querying values in nested mappings.

    You already show how to access the mapping containing the test3 key, you can simply query the value from there:

    ((Map<String, Object>)yamlFile.get("test2")).get("test3");
    

    However, it is much simpler to define the structure of your YAML file as class:

    class YamlFile {
        static class Inner {
            public String test3;
        }
    
        public String test1;
        public Inner test2;
    }
    

    Then you can load it like this:

    YamlFile file = new Yaml(new Constructor(YamlFile.class)).loadAs(
        input, YamlFile.class);
    file.test2.test3; // this is your string