I want to convert a json string to a List<Someclass>
using jackson json library.
我想使用jackson json库将json字符串转换为List
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>
.
因此,如果我将Attribute.class作为类型传递,那么它必须返回List
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.
我想泛型部分在这里我不清楚。任何帮助表示赞赏。
1 个解决方案
#1
4
you need to declare T
first in your generic method, In your case it would be :
你需要先在你的泛型方法中声明T,在你的情况下它将是:
public static <T> List<T> toList(String json, Class<T> type, ObjectMapperProperties objectMapperProperties)
for more info please check oracle documentation for generic methods:
有关更多信息,请查看oracle文档以获取通用方法:
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
#1
4
you need to declare T
first in your generic method, In your case it would be :
你需要先在你的泛型方法中声明T,在你的情况下它将是:
public static <T> List<T> toList(String json, Class<T> type, ObjectMapperProperties objectMapperProperties)
for more info please check oracle documentation for generic methods:
有关更多信息,请查看oracle文档以获取通用方法:
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html