1. 程式人生 > 實用技巧 >Jackson工具類

Jackson工具類

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import
java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Jackson 工具類 * <p>Title: MapperUtils</p> * <p>Description: </p> * * */ public class JacksonUtils { private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class
); private final static ObjectMapper objectMapper = new ObjectMapper(); public static ObjectMapper getInstance() { return objectMapper; } /** * 轉換為 JSON 字串 * * @param obj * @return * @throws Exception */ public static String obj2json(Object obj) throws
Exception { return objectMapper.writeValueAsString(obj); } /** * 將物件轉換為json字串 * @param obj * @return */ public static String obj2jsonStr(Object obj) { try { return JacksonUtils.obj2json(obj); } catch (Exception e) { logger.error("對像轉換成json字串報錯:", e); } return ""; } /** * 轉換為 JSON 字串,忽略空值 * * @param obj * @return * @throws Exception */ public static String obj2jsonIgnoreNull(Object obj) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.writeValueAsString(obj); } /** * 轉換為 JavaBean * * @param jsonString * @param clazz * @return * @throws Exception */ public static <T> T json2pojo(String jsonString, Class<? extends T> clazz) throws Exception { objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); return objectMapper.readValue(jsonString, clazz); } /** * 字串轉換為 Map<String, Object> * * @param jsonString * @return * @throws Exception */ public static <T> Map<String, Object> json2map(String jsonString) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.readValue(jsonString, Map.class); } /** * 字串轉換為 Map<String, T> */ public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) throws Exception { Map<String, Map<String, Object>> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, T>>() { }); Map<String, T> result = new HashMap<String, T>(); for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) { result.put(entry.getKey(), map2pojo(entry.getValue(), clazz)); } return result; } /** * 深度轉換 JSON 成 Map * * @param json * @return */ public static Map<String, Object> json2mapDeeply(String json) throws Exception { return json2MapRecursion(json, objectMapper); } /** * 把 JSON 解析成 List,如果 List 內部的元素存在 jsonString,繼續解析 * * @param json * @param mapper 解析工具 * @return * @throws Exception */ private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception { if (json == null) { return null; } List<Object> list = mapper.readValue(json, List.class); for (Object obj : list) { if (obj != null && obj instanceof String) { String str = (String) obj; if (str.startsWith("[")) { obj = json2ListRecursion(str, mapper); } else if (obj.toString().startsWith("{")) { obj = json2MapRecursion(str, mapper); } } } return list; } /** * 把 JSON 解析成 Map,如果 Map 內部的 Value 存在 jsonString,繼續解析 * * @param json * @param mapper * @return * @throws Exception */ private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) throws Exception { if (json == null) { return null; } Map<String, Object> map = mapper.readValue(json, Map.class); for (Map.Entry<String, Object> entry : map.entrySet()) { Object obj = entry.getValue(); if (obj != null && obj instanceof String) { String str = ((String) obj); if (str.startsWith("[")) { List<?> list = json2ListRecursion(str, mapper); map.put(entry.getKey(), list); } else if (str.startsWith("{")) { Map<String, Object> mapRecursion = json2MapRecursion(str, mapper); map.put(entry.getKey(), mapRecursion); } } } return map; } /** * 將 JSON 陣列轉換為集合 * * @param jsonArrayStr * @param clazz * @return * @throws Exception */ public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) throws Exception { JavaType javaType = getCollectionType(ArrayList.class, clazz); List<T> list = (List<T>) objectMapper.readValue(jsonArrayStr, javaType); return list; } /** * 獲取泛型的 Collection Type * * @param collectionClass 泛型的Collection * @param elementClasses 元素類 * @return JavaType Java型別 * @since 1.0 */ public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } /** * 將 Map 轉換為 JavaBean * * @param map * @param clazz * @return */ public static <T> T map2pojo(Map map, Class<T> clazz) { return objectMapper.convertValue(map, clazz); } /** * 將 Map 轉換為 JSON * * @param map * @return */ public static String mapToJson(Map map) { try { return objectMapper.writeValueAsString(map); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 將 JSON 物件轉換為 JavaBean * * @param obj * @param clazz * @return */ public static <T> T obj2pojo(Object obj, Class<T> clazz) { return objectMapper.convertValue(obj, clazz); } }