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.
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"));
}
public class YamlParser {
public YamlParser() {
}
public void parse(Map<String, Object> item, String parentKey) {
for (Entry entry : item.entrySet()) {
if (entry.getValue() != null && entry.getValue() instanceof Map) {
parse((Map<String, Object>) entry.getValue(),
(parentKey == null ? "" : parentKey + ".") + entry.getKey().toString());
} else {
System.out.println("map.put(\"" + (parentKey == null ? "" : parentKey + ".") + entry.getKey() + "\",\""
+ entry.getValue() + "\");");
}
}
}
public static void main(String[] args) {
try {
Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(
"path-to-application.yml");
Map<String, Object> obj = yaml.load(inputStream);
YamlParser parser = new YamlParser();
parser.parse(obj, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With