rholdberh
rholdberh

Reputation: 567

Read yaml to object using jackson

I have Yaml which looks like this:

data_lists:
      list1:(dynamic name)  
        - AA: true
          BB: true
          CC: "value"
        - AA: false
          BB: true
          CC: "value2"

What I am trying to get is to store it to the object

class BLA{
private boolean AA;
private boolean BB;
private String CC;

//getters and setters

}

I am using jackson library but I can found how to ignore root elements like data_lsts and lists1 and store only array objects.

My current code is:

ObjectMapper mapper = new ObjectMapper(YAML_FACTORY);
List<BLA> bla = Arrays.asList(mapper.readValue(ymlFile, BLA.class));

Upvotes: 1

Views: 6027

Answers (1)

Bentaye
Bentaye

Reputation: 9766

Given your example you can use a TypeReference and describe your file as Map<String, Map<String, List<BLA>>>

private static final String yamlString =
    "data_lists:\n" +
    "      list1:  \n" +
    "        - AA: true\n" +
    "          BB: true\n" +
    "          CC: \"value\"\n" +
    "        - AA: false\n" +
    "          BB: true\n" +
    "          CC: \"value2\"";

public static void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    Map<String, Map<String, List<BLA>>> fileMap = mapper.readValue(
        yamlString, 
        new TypeReference<Map<String, Map<String, List<BLA>>>>(){});
    Map<String, List<BLA>> dataLists = fileMap.get("data_lists");
    List<BLA> blas = dataLists.get("list1");
    System.out.println(blas);
}

class BLA {
    @JsonProperty("AA")
    private boolean aa;
    @JsonProperty("BB")
    private boolean bb;
    @JsonProperty("CC")
    private String cc;

    @Override
    public String toString() {
        return aa + "|" + bb + "|" + cc;
    }

    // Getters/Setters
}

This outputs

[true|true|value, false|true|value2]

If you have a list of lists like this:

data_lists:
  list1:  
    - AA: true
      BB: true
      CC: "value"
    - AA: false
      BB: true
      CC: "value2"
  list2:  
    - AA: true
      BB: true
      CC: "value3"
    - AA: false
      BB: true
      CC: "value4"

You can get "data_lists" values as a Collection

Map<String, List<BLA>> dataLists = fileMap.get("data_lists");
Collection<List<BLA>> blas = dataLists.values();
System.out.println(blas);

Outputs:

[[true|true|value, false|true|value2], [true|true|value3, false|true|value4]]

Upvotes: 3

Related Questions