0

I have this class:

public static class Version {
    @Getter private float version;
    @Getter private String url;
    @Getter private String label;
}

I am attempting to write a generic method for deserializing instances of this, and other classes, from JSON. So far I have:

private <T> List<T> deserializeJSONList(String json) {
    try {
        TypeReference reference = new TypeReference<List<T>>() {};
        return (List<T>) objectMapper.readValue(json, reference);
    } catch (JsonProcessingException e) {
        throw new RequestException(e);
    }
}

Which I call as:

List<Version> versions = deserializeJSONList(response.body());

The problem is that the returned List does not contain Version instances at all, but contains instances of LinkedHashMap, containing key/value pairs representing the fields.

How can I get the generic method to return a List containing objects of the correct type?

NickJ
  • 9,380
  • 9
  • 51
  • 74
  • Take a look on related question: [Refactor method to use generic for deserialization](https://stackoverflow.com/questions/57975814/refactor-method-to-use-generic-for-deserialization), [Deserializing or serializing any type of object using Jackson ObjectMapper and handling exceptions](https://stackoverflow.com/questions/56299558/deserializing-or-serializing-any-type-of-object-using-jackson-objectmapper-and-h), [How do I parametrize response parsing in Java?](https://stackoverflow.com/questions/57581859/how-do-i-parametrize-response-parsing-in-java) – Michał Ziober Nov 21 '19 at 14:37

1 Answers1

1

Use this method.

public static <T> List<T> fromJsonToList(String json, Class<T> clazz) throws IOException {
        CollectionType customClassCollection = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
        return objectMapper.readValue(json, customClassCollection);
    }
Vault23
  • 743
  • 1
  • 5
  • 19