Search code examples
javaarraysarraylistyamlsnakeyaml

Get Integer[] instead of ArrayList<Integer> from YAML file


I am parsing a YAML file

Props:
  Prop1 : [10, 22, 20]
  Prop2 : [20, 42, 60]

This gives me Map<String, Map<String, ArrayList<Integer>>> I would like to get Map<String, Map<String, Integer[]>> I do not want to convert List<Integer> to Integer[] in the code that reads the file. Can I change something in my YAML file?


Solution

  • In contrast to my other answer, this one focuses on changing the YAML file. However, you also need to add some Java code to tell SnakeYaml how to load the tag you use.

    You could add tags to the YAML sequences:

    Props:
      Prop1 : !intarr [10, 22, 20]
      Prop2 : !intarr [20, 42, 60]
    

    This need to be registered with SnakeYaml before loading:

    public class MyConstructor extends Constructor {
        public MyConstructor() {
            this.yamlConstructors.put(new Tag("!intarr"),
                                      new ConstructIntegerArray());
        }
    
        private class ConstructIntegerArray extends AbstractConstruct {
            public Object construct(Node node) {
                final List<Object> raw = constructSequence(node);
                final Integer[] result = new Integer[raw.size()];
                for(int i = 0; i < raw.size(); i++) {
                    result[i] = (Integer) raw.get(i);
                }
                return result;
            }
        }
    }
    

    You use it like this:

    Yaml yaml = new Yaml(new MyConstructor());
    Map<String, Map<String, Integer[]>> content =
        (Map<String, Map<String, Integer[]>>) yaml.load(myInput);