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.
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