SnakeYaml get stacked keys

淺唱寂寞╮ 提交于 2021-02-11 16:51:26

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/60135911/snakeyaml-get-stacked-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!