Search code examples
javajsonlistgenericsobjectmapper

Returning a Generic list from JsonNode using an Object Mapper?


I have the following code that returns a list of strings from a JsonNode:

   public static List<String> asList(final JsonNode jsonNode) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(jsonNode, ArrayList.class);
    }

Example usage:

 List<String> identities = Utils.asList(jsonNode);

I want to change this to use Generics to ensure that a JsonNode contain a list of any Type can also be converted and returned.

I have the below implementation (not uses Jackson ObjectMapper), but is this the optimal solution?

public static <T> List<T> asList(final JsonNode jsonNode) {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.convertValue(jsonNode, ArrayList.class);
}

Solution

  • You can create a util method that accepts JSON string and TypeReference

    public <T> T jsonMapper(String json, TypeReference<T> typeReference)
            throws JsonParseException, JsonMappingException, IOException {
        return objectMapper.readValue(json, typeReference);
    }
    

    For example you can call this method either to convert json string to List or single Object

    List<String> lOfStr = jsonMapper(json,new TypeReference<List<String>>() { });
    Employee emp = jsonMapper(json,new TypeReference<Employee>() { });