问题
public static <T> List<T> convertJSONStringTOListOfT(String jsonString, Class<T> t){
if(jsonString == null){
return null;
}
ObjectMapper mapper = new ObjectMapper();
try
{
List<T> list = mapper.readValue(jsonString, new TypeReference<List<T>>() {});
return list;
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I have the above method, when I try to invoke it using :
list = convertJSONStringTOListOfT(str, CustomAssessmentQuestionSetItem.class);
The returned list is List<LinkedHashMap>
not List<CustomAssessmentQuestionSetItem>
Although if I don't use generics then the below code works fine :
list = mapper.readValue(str, new TypeReference<List<CustomAssessmentQuestionSetItem>>() {});
Both invocations appear the same to me. Unable to understand why the generic one is creating a List<LinkedHashMap>
instead of List<CustomAssessmentQuestionSetItem>
FYI : I've also tried changing the method signature to
public static <T> List<T> convertJSONStringTOListOfT(String jsonString, T t)
and the corresponding invocation to
list = convertJSONStringTOListOfT(str,new CustomAssessmentQuestionSetItem());
but it didn't worked.
回答1:
Since you have the element class you probably want to use your mapper's TypeFactory
like this:
final TypeFactory factory = mapper.getTypeFactory();
final JavaType listOfT = factory.constructCollectionType(List.class, t);
Then use listOfT
as your second argument to .readValue()
.
来源:https://stackoverflow.com/questions/29242530/jackson-generic-json-to-listt-converter-method-does-not-work