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

Alok picture Alok · Feb 12, 2018 · Viewed 14.2k times · Source

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.

Answer

Devstr picture Devstr · Feb 12, 2018

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

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