【问题标题】:How can I grab a value from an ArrayList nested in a LinkedHashMap?如何从嵌套在 LinkedHashMap 中的 ArrayList 中获取值?
【发布时间】:2022-11-26 05:35:32
【问题描述】:

我目前有一个如下所示的 yaml 文件:

description: this-apps-config
options:
  - customer: joe
    id: 1
    date: 2022-01-01
    print: False
  - customer: jane
    id: 2
    date: 2022-01-02
    print: True

我能够使用 snakeyaml 成功阅读此内容:

Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("file.yml"));
Map<String, Object> data = yaml.load(inputStream);
System.out.println(data);

上面的代码将所有内容作为 LinkedHashMap 检索,options 是另一个 HashMap 的 ArrayList,如下所示:

{description=this-apps-config, options=[{customer=joe, id=1, date=2022-01-01, print=False}, {customer=jane, id=2, date=2022-01-02, print=True}]}

我的问题是,如何在每个options 中获取print 值?我得到的最接近的是:

ArrayList<Object> al = new ArrayList<>()
al.add(data.get("options"))

不过,这只会让我首先看到 options ArrayList。不确定如何更深入。

谢谢

【问题讨论】:

    标签: java yaml snakeyaml


    【解决方案1】:

    YAML 允许您将文件加载到自定义类中,并支持包含其他类型(包括集合)字段的顶级类型。尝试以下操作:

    public class MyYaml {
    
        private String description;
        private List<Customer> options;
    
        // getters and setters
    }
    
    public class Customer {
    
        private String customer;
        private int id;
        private Date date;
        private boolean print;
    
        // getters and setters
    }
    

    然后你想加载文件的位置:

    Yaml yaml = new Yaml();
    InputStream inputStream = this.getClass()
     .getClassLoader()
     .getResourceAsStream("myFile.yaml");
    MyYaml myYaml = yaml.load(inputStream);
    

    Here 是一个可能对你有帮助的相关教程。

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2020-08-14
      相关资源
      最近更新 更多