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

北慕城南 提交于 2019-12-06 11:35:41

问题


I am trying to read config.yaml file using the snakeYaml library in java.

I am able to get the Module name (i.e [{ABC=true}, {PQR=false}]) in my config file. Is there a way where I can directly read the value of ABC (ie true) using the code.

I have tried to search online but they are not exactly what I am looking for. Few links that I went through mentioned below:

Load .yml file into hashmaps using snakeyaml (import junit library)

https://www.java-success.com/yaml-java-using-snakeyaml-library-tutorial/

config.yaml data:

Browser: FIREFOX
Module Name:
- ABC: Yes
- PQR: No

Below is the code that I am using

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;

public class YAMLDemo {

    public static void main(String[] args) throws FileNotFoundException {

        Yaml yaml = new Yaml();
        Reader yamlFile = new FileReader("./config.yaml");

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

        System.out.println(yamlMaps.get("Browser"));
        System.out.println(yamlMaps.get("Module Name"));
    }
}

Console Output:

FIREFOX
[{ABC=true}, {PQR=false}]

Any help is really appreciated. Thanks in advance.


回答1:


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"));
}



回答2:


@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"));


来源:https://stackoverflow.com/questions/48744919/how-to-access-the-innernested-key-value-in-an-yaml-file-using-snakeyaml-librar

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