javayamljava-11apache-commons-config

How to read a list from a YAMLConfigutation


I have a YAML file that looks like this:

foo:
  bar:
    - entry1: 1
      entry2: a
    - entry1: 2
      entry2: b

(Where the actual list is much longer.) I'm reading this file using Apache Configuration2's YAMLConfiguration. I can see the data in the internal data structures used in Apache Configuration2, but I can't figure out how to get this list out. I actually have a class that matches the structure of the list elements, which is what I'd really like to read into:

class MyListEntry {
    public int entry1;
    public String entry2;
}

How can I get the data YAMLConfiguration into a List<MyListEntry>?


Solution

  • Here's the solution I found (note this works for any HierarchicalConfiguration, not just YAMLConfiguration)

    // this will return a list of List<HierarchicalConfiguration<ImmutableNode>>, one entry for each element of the list
    var subConfigList = hierarchicalConfig.configurationsAt("foo.bar");
    
    List<MyListEntry> myListEntries = new ArrayList<>(subConfigList.size());
    // iterate over the subconfigs and pull out the specific values of interest
    for(var subConfig : subconfigs) {
        MyListEntry myListEntry = new MyListEntry();
        myListEntry.entry1 = subConfig.getInt("entry1");
        myListEntry.entry2 = subConfig.getString("entry2");
        myListEntries.add(myListEntry);    
    }