简体   繁体   中英

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

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM