0

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.

Saturnian
  • 1,686
  • 6
  • 39
  • 65
  • But any reason why you want to read yml urself. springboot is capable of converting your yml to object list. You can do this using `@ConfigurationProperties`. – pvpkiran Jun 14 '18 at 09:52
  • @pvpkiran Could you illustrate it with a small example? – Saturnian Jun 14 '18 at 16:29
  • have a look at this question and my answer https://stackoverflow.com/questions/50837283/mapping-list-in-yaml-file-to-list-of-objects/50837946?noredirect=1#comment88682164_50837946 – pvpkiran Jun 14 '18 at 20:17
  • This looks great! But where do you specify which YAML file to read from? And where from do you obtain the list object? – Saturnian Jun 14 '18 at 20:43
  • create a file by name application.yml under resources folder. Rest will be taken care by springboot. Do upvote if that answer helped. – pvpkiran Jun 14 '18 at 20:44
  • I cannot do that, i have to read from specific files every time. I specify each time which file to read from. Adding `@Configuration` & `@ConfigurationProperties` hasn't helped at all – Saturnian Jun 14 '18 at 21:17
  • tra with `@ImportResource` – pvpkiran Jun 15 '18 at 09:06

0 Answers0