public final ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws Exception{ String jsonString = getJsonString(); //getConfig省略 //List<Config> configList = (List<Config>)jsonString //上面这样转换是错的,但是编译没有报错,运行时才报错 JavaType javaType = getCollectionType(ArrayList.class, Config.class); List<Config> configList = mapper.readValue(jsonString, javaType); //这里不需要强制转换 } /** * 获取泛型的Collection Type * @param collectionClass 泛型的Collection * @param elementClasses 元素类 * @return JavaType Java类型 * @since 1.0 */ public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); }
注意最后的方法啊