且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将json转换为对象列表时发生ClassCastException

更新时间:2023-01-17 19:45:43

您可能要做的***的事情就是为Collection类型支持一种通用方法,为非Collection类型支持其他通用方法.

The best you can probably do is to support one generic method for Collection types, and possibly others for non-Collection types.

这是通用Collection方法的工作版本:

Here's a working version of the generic Collection method:

import org.codehaus.jackson.map.type.TypeFactory;

//...

@SuppressWarnings({ "deprecation", "rawtypes" })
public static <E, T extends Collection> T parseJsonToObject(String jsonStr, Class<T> collectionType, Class<E> elementType) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(jsonStr, TypeFactory.collectionType(collectionType, elementType));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null; 
}

然后您将这样称呼:

List<Person> persons = parseJsonToObject(s, ArrayList.class, Person.class);