杰克逊通用json到List< T>转换器方法不起作用 [英] Jackson generic json to List<T> converter method does not work

查看:380
本文介绍了杰克逊通用json到List< T>转换器方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

返回的列表是列表< LinkedHashMap> 不是列表< CustomAssessmentQuestionSetItem>

虽然如果我不使用泛型,那么下面的代码可以正常工作:

Although if I don't use generics then the below code works fine :

list = mapper.readValue(str, new TypeReference<List<CustomAssessmentQuestionSetItem>>() {});

两次调用对我来说都是一样的。无法理解为什么通用的创建列表< LinkedHashMap> 而不是列表< 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)

以及相应的调用

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

但它没有用。

推荐答案

由于你有元素类,你可能想要使用你的映射器的 TypeFactory ,如下所示:

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);

然后使用 listOfT 作为你的第二个参数 .readValue()

Then use listOfT as your second argument to .readValue().

这篇关于杰克逊通用json到List&lt; T&gt;转换器方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆