Search code examples
javayamlobjectmapper

YAML parsed as linkedHashMap not as JAVABean


I have a YAML that should be parsed as JAVA POJO object instead its throwing a java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to <mytype>. The YAML is as below :

--- 
- 
  count: 1
  indicies: 
    - be-log-2018.09.20
  searchText: someText
  services: 
    - um
    - sa
- 
  count: 2
  searchText: someMoreText
  services: 
    - um2
    - sa2
- 
  count: 2
  searchText: someMoreText

My POJO class is :

public class MyType {

    private int count;
    private String searchText;
    private String[] services;
    private String[] indicies;

and reading the YAML with :

ObjectMapper mapper= new ObjectMapper(new YAMLFactory());
mapper.readValue(new File(path), List.class);

Ideally I want to have a empty array if no data is given.


Solution

  • Use this

    List<MyType> myTypeList = objectMapper.readValue(new File(path), new TypeReference<List<MyType>>() {});
    

    Read more about TypeReference