Parsing Yaml in Java

Damien-Amen picture Damien-Amen · Nov 27, 2017 · Viewed 8.7k times · Source

I have the following YAML I want to parse using Jackson parser in Java.

android:
    "7.0":
        - nexus
        - S8
    "6.0":
        - s7
        - g5
ios:
    "10.0":
        - iphone 7
        - iphone 8

I created a created class which has getter and setter as Java Object for android. It works fine. But how do I do the same for 6.0 and 7.0? I'm usingJackson` Parser

Answer

flyx picture flyx · Nov 28, 2017

No idea whether Jackson supports that; here's a solution with plain SnakeYaml (I will never understand why people use Jackson for parsing YAML when all it does is basically take away the detailed configuration possible with SnakeYaml which it uses as backend):

class AndroidValues {
     // showing what needs to be done for "7.0". "8.0" works similarly.
     private List<String> v7_0;

     public List<String> getValuesFor7_0() {
         return v7_0;
     }

     public void setValuesFor7_0(List<String> value) {
         v7_0 = value;
     }
}

// ... in your loading code:

Constructor constructor = new Constructor(YourRoot.class);
TypeDescription androidDesc = new TypeDescription(AndroidValues.class);
androidDesc.substituteProperty("7.0", List.class, "getValuesFor7_0", "setValuesFor7_0");
androidDesc.putListPropertyType("7.0", String.class);
constructor.addTypeDescription(androidDesc);
Yaml yaml = new Yaml(constructor);

// and then load the root type with it

Note: Code has not been tested.