[英]Jackson generic json to List<T> converter method does not work
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;
}
當我嘗試使用以下方法調用它時,我具有上述方法:
list = convertJSONStringTOListOfT(str, CustomAssessmentQuestionSetItem.class);
返回的列表是List<LinkedHashMap>
而不是List<CustomAssessmentQuestionSetItem>
雖然如果我不使用泛型,則以下代碼可以正常工作:
list = mapper.readValue(str, new TypeReference<List<CustomAssessmentQuestionSetItem>>() {});
兩種調用對我來說似乎都是相同的。 無法理解為什么通用類為什么要創建一個List<LinkedHashMap>
而不是List<CustomAssessmentQuestionSetItem>
僅供參考:我還嘗試過將方法簽名更改為
public static <T> List<T> convertJSONStringTOListOfT(String jsonString, T t)
以及相應的調用
list = convertJSONStringTOListOfT(str,new CustomAssessmentQuestionSetItem());
但是沒有用。
由於您具有元素類,因此您可能希望像這樣使用映射器的TypeFactory
:
final TypeFactory factory = mapper.getTypeFactory();
final JavaType listOfT = factory.constructCollectionType(List.class, t);
然后使用listOfT
作為.readValue()
第二個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.