Jackson将json串转成List或Map等集合

时间:2025-03-15 15:12:39

Jackson将json串转成List、Map等集合时,需要保证集合内的元素泛型不能丢失。
方法一:
此方法每次都需要构建TypeReference参数,比较麻烦,也不够美观,因此不推荐这种方式

public static <T> T json2Obj(String json, TypeReference<T> type) {
    return objectMapper.readValue(json, type);
}
// 使用
json2Obj(json, new TypeReference<List<String>>(){});
json2Obj(json, new TypeReference<Map<String, String>>(){});

方法二:(推荐)

private static JavaType collectionType(Class<?> collectionClz, Class<?> ...elementClz) {
    return om.getTypeFactory().constructParametricType(collectionClz, elementClz);
}
public static List<T> json2List(String json, Class<T> elementClz) {
    objectMapper.readValue(json, collectionType(List.class, clz));
}
public static List<T> json2Map(String json, Class<T> valueClz) {
    objectMapper.readValue(json, collectionType(Map.class, String.class, clz));
}
// 使用
json2List(json, String.class);
json2Map(json. String.class);