import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import java.io.IOException; /** * Json序列化與反序列化工具類 */ public class JsonUtil { private static final ObjectMapper objectMapper = new ObjectMapper(); /** * 對象轉JSON * * @param t * 對象 * @return */ public static <T> String toJson(T t){ try { return objectMapper.writeValueAsString(t); }catch (IOException e){ throw new RuntimeException("JsonUtil.toJson error",e); } } /** * JSON轉對象 * * @param jsonString * json字符串 * @param valueType * 對象類型 * @return */ public static <T> T fromJson(String jsonString, Class<T> valueType) { if (StringUtils.isBlank(jsonString)) { return null; } try { return objectMapper.readValue(jsonString, valueType); } catch (IOException e) { throw new RuntimeException("JsonUtil.fromJson error", e); } } /** * * @param jsonString * json字符串 * @param typeReference * 泛型信息 * @return */ public static <T> T fromJson(String jsonString, TypeReference<T> typeReference) { if (StringUtils.isBlank(jsonString)) { return null; } try { return objectMapper.readValue(jsonString, typeReference); } catch (IOException e) { throw new RuntimeException("JsonUtil.fromJson error", e); } } /** * 判斷是否json 字符串 * @param str * @return */ public static boolean isJsonString(String str) { if(StringUtils.isBlank(str)){ return false; } try { objectMapper.readTree(str); return true; } catch (IOException e) { return false; } } }