java json轉換工具類
阿新 • • 發佈:2018-11-10
在java專案中,通常會用到json型別的轉換,常常需要對 json字串和物件進行相互轉換。
在製作自定義的json轉換類之前,先引入以下依賴
<!--json解析工具--> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-guava</artifactId> <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工具類的實現:
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; } } }