So, I have a YAML file like this:
- code: QWERTY1
name: qwerty-name
desc: a qwerty desc
- code: QWERTY2
name: qwerty-name-2
desc: a qwerty desc 2
And I am trying to read this as list of MyObject
using jackson
.
My Java code looks like this:
public <T, K> List<K> readSerializedList(File f, Class<T> formatType, Class<K> classType) throws IOException{
ObjectMapper MAPPER = new ObjectMapper(new YAMLFactory());
try {
final T result = MAPPER.readValue(f, formatType);
List<K> myList = MAPPER.convertValue(result, new TypeReference<List<K>>() { });
return myList;
} catch (JsonParseException | JsonMappingException | InvalidKeyException e) {
throw new IOException(e);
}
}
and I call it from another function like this:
readSerializedList(new File("path/to/file/a.yaml"), List.class, MyObject.class)
Instead of obtaining a list of MyObject
, I obtain a LinkedHashMap
.
If I explicitly change line 4 to :
List<MyObject> myList = MAPPER.convertValue(result, new TypeReference<List<MyObject>>() { });
then I obtain a list of MyObject
.
I need that kind of generalization that I'm trying to achieve because the design is such that, readSerializedList()
should be able to read from YAML any kind of list we tell it to.
Is there a way to achieve this? I'm using Springboot with Java 8.