【发布时间】:2016-06-07 22:05:23
【问题描述】:
我想使用 jackson json 库将 json 字符串转换为 List<Someclass>。
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();
}
}
所以如果我将Attribute.class 传递为type,那么它必须返回一个List<Attribute>。
但是,这给了我一个编译时错误
T cannot be resolved to a type
我猜泛型部分在这里对我来说不是很清楚。任何帮助表示赞赏。
【问题讨论】:
-
问题在于编译器上下文中的“T”可能是任何其他类型。使用字母 T U V 是我们用于泛型的约定,但您也可以轻松地写成 List
。为了告诉编译器它是泛型的,你必须做一些事情来区分它,否则它只是一个无法解析的类型。
标签: java json generics jackson objectmapper