12

I want to convert a json string to a List<Someclass> using jackson json library.

public static List<T> toList(String json, Class<T> type, ObjectMapperProperties objectMapperProperties){

        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(objectMapperProperties);

        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, type));
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

So if I pass Attribute.class as type, then it must return a List<Attribute>.

However, this gives me a compile time error

T cannot be resolved to a type

I guess generics part is not clear to me here. Any help is appreciated.

kometen
  • 6,536
  • 6
  • 41
  • 51
Siddharth Trikha
  • 2,648
  • 8
  • 57
  • 101
  • 1
    The problem lies in the fact that "T" in the context of the compiler could be a type like any other. Using letters T U V are conventions that we use for generics, but you could just as easily write List instead. In order to tell the compiler it is a generic, you have to do something to distinguish it, otherwise it is just a type that can't be resolved. – Neil Feb 25 '16 at 08:57

1 Answers1

27

you need to declare T first in your generic method, In your case it would be :

public static <T> List<T> toList(String json, Class<T> type,  ObjectMapperProperties objectMapperProperties)

for more info please check oracle documentation for generic methods:

https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45