【问题标题】:YAML values not getting returned correctlyYAML 值未正确返回
【发布时间】:2015-09-02 23:27:36
【问题描述】:

我有一个如下所示的 YAML 文件:

---
name:
  storage:
    documentfiles:
      username: rafa
      password: hello

我正在尝试获取最后两个 usernamepassword 值。我当前的代码是下面的代码。我正在使用 Map 来存储 YAML 值,但是由于当我 map.get() 超过 name 时有多个孩子,所以它给了我一个空值。如果我这样做map.get(name) 我得到{storage={documentfiles={username=rafa, password=hello}}} 有谁知道我怎样才能正确获取用户名和密码?

public Map grabYaml(){
    Yaml reader = new Yaml();

    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(yamlFileName);
    Map map = (Map) reader.load(inputStream);

    return map;
}

【问题讨论】:

    标签: java configuration yaml


    【解决方案1】:

    类似的东西

    public class Test {
    
        public Map grabYaml() throws IOException {
            Yaml reader = new Yaml();
    
            InputStream inputStream = new FileInputStream(new File(yamlFileName));
            Map map = (Map) reader.load(inputStream);
    
            return map;
        }
    
        public static void main(String[] args) throws IOException {
            Map storage = (Map) new Test().grabYaml().get("name");
            Map documentfiles = (Map)storage.get("storage");
            Map userData = (Map) documentfiles.get("documentfiles");
    
            System.out.println(userData.get("username"));
            System.out.println(userData.get("password"));
        }
    }
    

    【讨论】:

    • 第一行的obj 是从哪里得到的?
    • 类的实例变量
    • 我正在从它创建的同一个类中调用grabYaml()。无论如何,使用该结构,它仍然给我documentfiles 行上的空指针异常。
    • @ralphie9224 我更新了我的完整课程,希望对您有所帮助。
    猜你喜欢
    • 2019-11-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多