123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198 |
- package com.lote.wms.common.utils;
- import com.fasterxml.jackson.annotation.JsonInclude;
- import com.fasterxml.jackson.core.JsonGenerationException;
- import com.fasterxml.jackson.core.JsonGenerator;
- import com.fasterxml.jackson.core.JsonParseException;
- import com.fasterxml.jackson.core.JsonParser;
- import com.fasterxml.jackson.databind.*;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.IOException;
- import java.io.StringWriter;
- import java.util.List;
- import java.util.Map;
- /**
- * @author Scott Chen
- * @version 1.0
- * 2017-09-18 18:42
- */
- public class JacksonUtil {
- private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
- private static ObjectMapper objectMapper;
- private static final ThreadLocal<ObjectMapper> objectMapperThreadLocal = new ThreadLocal<>();
- /**
- * 禁止调用无参构造
- *
- * @throws IllegalAccessException
- */
- private JacksonUtil() throws IllegalAccessException {
- throw new IllegalAccessException("Can't create an instance!");
- }
- public static ObjectMapper newObjectMapper() {
- objectMapper = objectMapperThreadLocal.get();
- if (objectMapper == null) {
- objectMapper = getObjectMapper();
- objectMapperThreadLocal.set(objectMapper);
- }
- return objectMapper;
- }
- /**
- * 懒惰单例模式得到ObjectMapper实例
- * 此对象为Jackson的核心
- */
- private static final ObjectMapper getObjectMapper() {
- if (objectMapper== null){
- objectMapper= new ObjectMapper();
- //序列化时,如果没有为类型找到访问者,则会抛出异常以将其指定为非可序列化类型; 如果禁用,它们将被序列化为空对象
- objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
- //反序列化时,遇到未知属性是否抛JsonMappingException异常.默认JsonMappingException
- objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- //设置null值不参与序列化(字段不被显示)
- objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
- }
- return objectMapper;
- }
- //-------------------- 序列化 --------------------
- /**
- * 创建JSON生成器
- * 序列化 writing JSON content
- * @return
- */
- private static JsonGenerator getGenerator(StringWriter sw){
- try{
- return getObjectMapper().getFactory().createGenerator(sw);
- }catch (IOException e) {
- return null;
- }
- }
- /**
- * 创建JSON处理器
- * 反序列化 reading JSON content
- * @param content JSON字符串
- * @return
- */
- private static JsonParser getParser(String content){
- try{
- return getObjectMapper().getFactory().createParser(content);
- }catch (IOException ioe){
- return null;
- }
- }
- /**
- * 对象序列化
- */
- public static String toJSON(Object obj){
- StringWriter sw= new StringWriter();
- JsonGenerator jsonGen= getGenerator(sw);
- if (jsonGen== null){
- try {
- sw.close();
- } catch (IOException e) {
- }
- return null;
- }
- try {
- //由于在getGenerator方法中指定了OutputStream为sw
- //因此调用writeObject会将数据输出到sw
- jsonGen.writeObject(obj);
- //由于采用流式输出 在输出完毕后务必清空缓冲区并关闭输出流
- jsonGen.flush();
- jsonGen.close();
- return sw.toString();
- } catch (JsonGenerationException jge) {
- logger.error("toJSON序列化失败, 异常类型【JsonGenerationException】,错误原因:%s", jge.getMessage());
- } catch (IOException ioe) {
- logger.error("toJSON序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage());
- }
- return null;
- }
- /**
- * JSON反序列化
- */
- public static <T> T fromJSON(String json, Class<T> clazz) {
- try {
- JsonParser jp= getParser(json);
- return jp.readValueAs(clazz);
- } catch (JsonParseException jpe){
- logger.error(String.format("fromJSON反序列化失败, 异常类型【JsonParseException】, 错误原因:%s", jpe.getMessage()));
- } catch (JsonMappingException jme){
- logger.error(String.format("fromJSON反序列化失败, 异常类型【JsonMappingException】, 错误原因:%s", jme.getMessage()));
- } catch (IOException ioe){
- logger.error(String.format("fromJSON反序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage()));
- }
- return null;
- }
- /**
- * JSON反序列化为List
- *
- * @param json
- * @param collectionClass
- * @param elementClass
- * @return
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- public static <T> List<T> toList(String json, Class<? extends List> collectionClass, Class<T> elementClass) {
- JavaType javaType = getObjectMapper().getTypeFactory().constructCollectionType(collectionClass, elementClass);
- try{
- return getObjectMapper().readValue(json, javaType);
- } catch (JsonParseException jpe){
- logger.error(String.format("toList反序列化失败, 异常类型【JsonParseException】, 错误原因:%s", jpe.getMessage()));
- } catch (JsonMappingException jme){
- logger.error(String.format("toList反序列化失败, 异常类型【JsonMappingException】, 错误原因:%s", jme.getMessage()));
- } catch (IOException ioe){
- logger.error(String.format("toList反序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage()));
- }
- return null;
- }
- /**
- * JSON反序列化为Map
- *
- * @param json
- * @param mapClass
- * @param keyClass
- * @param valueClass
- * @return
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- public static <K, V> Map<K, V> toMap(String json, Class<? extends Map> mapClass, Class<K> keyClass,
- Class<V> valueClass) throws JsonParseException, JsonMappingException, IOException {
- JavaType javaType = getObjectMapper().getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
- try{
- return getObjectMapper().readValue(json, javaType);
- }catch (JsonParseException jpe){
- logger.error(String.format("toMap反序列化失败, 异常类型【JsonParseException】, 错误原因:%s", jpe.getMessage()));
- } catch (JsonMappingException jme){
- logger.error(String.format("toMap反序列化失败, 异常类型【JsonMappingException】, 错误原因:%s", jme.getMessage()));
- } catch (IOException ioe){
- logger.error(String.format("toMap反序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage()));
- }
- return null;
- }
- }
|