更新时间: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);