Jackson generic json to List<T> converter method does not work

为君一笑 提交于 2019-12-11 11:18:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!