如何使用snakeYaml库访问YAML文件中的内部(嵌套)键值 [英] How to Access the inner(nested) key-value in an YAML file using snakeYaml Library

查看:885
本文介绍了如何使用snakeYaml库访问YAML文件中的内部(嵌套)键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java中的snakeYaml库读取config.yaml文件.

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

我可以在我的配置文件中获取模块名称(即[{ABC=true}, {PQR=false}]). 有没有办法我可以使用代码直接读取ABC的值(即true).

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:

使用snakeyaml将.yml文件加载到哈希图中(导入junit库)

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

config.yaml 数据:

config.yaml data:

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

下面是我正在使用的代码

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

控制台输出:

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

我们非常感谢您的帮助.预先感谢.

Any help is really appreciated. Thanks in advance.

推荐答案

如果使用调试器浏览代码,则可以看到module_name被反序列化为ArrayList<LinkedHashMap<String, Object>>:

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

这篇关于如何使用snakeYaml库访问YAML文件中的内部(嵌套)键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆