Jackson将json串转成List、Map等集合时,需要保证集合内的元素泛型不能丢失。
方法一:
此方法每次都需要构建TypeReference参数,比较麻烦,也不够美观,因此不推荐这种方式
public staticT json2Obj(String json, TypeReference type) { return objectMapper.readValue(json, type); } // 使用 json2Obj(json, new TypeReference >(){}); json2Obj(json, new TypeReference
方法二:(推荐)
private static JavaType collectionType(Class> collectionClz, Class> ...elementClz) {
return om.getTypeFactory().constructParametricType(collectionClz, elementClz);
}
public static List json2List(String json, Class elementClz) {
objectMapper.readValue(json, collectionType(List.class, clz));
}
public static List json2Map(String json, Class valueClz) {
objectMapper.readValue(json, collectionType(Map.class, String.class, clz));
}
// 使用
json2List(json, String.class);
json2Map(json. String.class);



