我正在使用jackson ObjectMapper
将json字符串转换为POJO
objectMapper.readValue(jsonString, ResourceTypes.getClassName(resourceType))
ResourceTypes.getClassName(resourceType)
返回不同的类名。
例如:Student.class、Hotel.class等
现在我想为这个写一个通用函数,比如:
public static T toPOJO(String json, Class<T> type){
try {
return JSON_MAPPER.readValue(json, type);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
然而,这给出了未知类型的错误T
。如何编写此函数来返回任何POJO?
试试这个,也许这会起的作用
public static <T> T toPOJO(String json, Class<T> type) {
try {
return JSON_MAPPER.readValue(json, type);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
有任何问题请告诉我。