How to Access the inner(nested) key-value in an YAML file using snakeYaml Library

喜欢而已 提交于 2019-12-04 15:47:10

If you step through the code with a debugger, you can see that module_name is deserialised as an ArrayList<LinkedHashMap<String, Object>>:

You just need to cast it to the correct type:

public static void main(String[] args) throws FileNotFoundException {
    Yaml yaml = new Yaml();
    Reader yamlFile = new FileReader("./config.yaml");

    Map<String , Object> yamlMaps = (Map<String, Object>) yaml.load(yamlFile);

    System.out.println(yamlMaps.get("Browser"));
    final List<Map<String, Object>> module_name = (List<Map<String, Object>>) yamlMaps.get("Module Name");
    System.out.println(module_name);
    System.out.println(module_name.get(0).get("ABC"));
    System.out.println(module_name.get(1).get("PQR"));
}

@Devstr has provided you With a good description on how to figure out the data structures. Here you have an example of how you can read the values into a Properties Object:

final Properties modules = new Properties();

final List<Map<String, Object>> values = (List<Map<String, Object>>) yamlMaps.get("Module Name");

values.stream().filter(Objects::nonNull)
               .flatMap(map -> map.entrySet().stream())
               .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
               .forEach((key, value) -> {
                   modules.put(key, value);
               });

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