1
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>>() {});

两种调用对我来说都是一样的。无法理解为什么通用创建的是 aList<LinkedHashMap>而不是List<CustomAssessmentQuestionSetItem>

仅供参考:我也尝试将方法签名更改为

public static <T> List<T> convertJSONStringTOListOfT(String jsonString, T t)

以及相应的调用

list = convertJSONStringTOListOfT(str,new CustomAssessmentQuestionSetItem());

但它没有奏效。

4

1 回答 1

5

既然你有元素类,你可能想像这样使用你的映射器TypeFactory

final TypeFactory factory = mapper.getTypeFactory();
final JavaType listOfT = factory.constructCollectionType(List.class, t);

然后listOfT用作您的第二个参数.readValue()

于 2015-03-24T21:00:28.177 回答