import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import java.io.IOException; /** * Json serialization and de-serialization Tools * / Public class JsonUtil { private static final ObjectMapper objectMapper = new ObjectMapper(); /** * Turn JSON objects * * @param t * Object * @return */ public static <T> String toJson(T t){ try { return objectMapper.writeValueAsString(t); }catch (IOException e){ throw new RuntimeException("JsonUtil.toJson error",e); } } /** * JSON objects turn * * @Param jsonString * Json string * @param valueType * Object Type * @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 string * @Param type reference * Generic information * @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); } } /** Determining whether the string * json * @Param Cycle * @return */ public static boolean isJsonString(String str) { if(StringUtils.isBlank(str)){ return false; } try { objectMapper.readTree(str); return true; } catch (IOException e) { return false; } } }