1、需求描述
jackson 将 json 串转成 List、Map 等集合时,需要保证集合内的元素泛型不能丢失。
2、案例
1)需要构建 TypeReference 参数
1 2 3 4 5 6 7
| 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>>(){});
|
2)collectionType
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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);
|
3)其他方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public final class JsonUtils { private static ObjectMapper jackson = new ObjectMapper();
public static Map jsonToMap(String jsonStr) { Map map = new HashMap<String,Object>(); try { map = jackson.readValue(jsonStr, HashMap.class); } catch (IOException e) { e.printStackTrace(); } return map; }
public static List jsonToList(String jsonStr) { List list = new ArrayList<>();
try { list = jackson.readValue(jsonStr,ArrayList.class); } catch (IOException e) { e.printStackTrace(); } return list; } }
|