在java項目中,一般會用到json類型的轉換,經常須要對 json字符串和對象進行相互轉換。java
在製做自定義的json轉換類以前,先引入如下依賴json
<!--json相關工具--> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-guava</artifactId> <!--google--> <version>2.5.3</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
自定義json工具類的實現:app
package com.me.util; import lombok.extern.slf4j.Slf4j; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider; import org.codehaus.jackson.type.TypeReference; /** * json轉換 */ @Slf4j public class JsonMapper { private static ObjectMapper objectMapper = new ObjectMapper(); static { // config objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false); objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false)); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); } /** * 對象轉爲json字符串 * @param src * @param <T> * @return */ public static <T> String obj2String(T src){ if(src == null){ return null; } try{ return src instanceof String ? (String) src : objectMapper.writeValueAsString(src); } catch (Exception e) { log.warn("parse object to String exception",e); return null; } } /** * json字符串轉爲對象 * @param src * @param typeReference * @param <T> * @return */ public static <T> T string2Obj(String src, TypeReference<T> typeReference) { if (src == null || typeReference == null) { return null; } try { return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference)); } catch (Exception e) { log.warn("parse String to Object exception, String:{}, TypeReference<T>:{}, error:{}", src, typeReference.getType(), e); return null; } } }
使用:ide
JSON串轉爲list類型工具
對象類型轉爲JSON串google