Springboot2以代码的方式统一配置Jackson教程

 更新时间:2021年11月30日 08:42:14   投稿:jingxian  
这篇文章主要介绍了Springboot2以代码的方式统一配置Jackson教程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

说明

本文主要配置Jackson对Long、Date、LocalDate、LocalDateTime的序列化和反序列化。

由于js中整数可精确表示范围小于java Long的范围,故将Long序列化为String,反序列化Jackson会自动处理String转Long,故不需要显式配置。

由于时间戳在各语言间的兼容性良好,故将Date、LocalDate、LocalDateTime序列化为Long(目前时间戳类的Long类型在js的可精确表示范围内),将Long反序列化为Date、LocalDate、LocalDateTime。将String空字符串反序列化为null。

本文除了配置Springboot整合的Jackson,还配置了功能一致的Jackson工具类,方便在代码中显示使用Jackson的序列化和反序列化功能。

7个序列化和反序列化规则

package com.xxx.config.serializers;
import java.io.IOException;
import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class DateSerializer extends JsonSerializer<Date> {
 @Override
 public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  if (value != null) {
   gen.writeNumber(value.getTime());
  }
 }
}
package com.xxx.config.serializers;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LocalDateSerializer extends JsonSerializer<LocalDate> {
 @Override
 public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  if (value != null) {
   long millis = value.atStartOfDay(ZoneId.of("+8")).toInstant().toEpochMilli();
   gen.writeNumber(millis);
  }
  }  
   }
package com.xxx.config.serializers;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
 @Override
 public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  if (value != null) {
   long millis = value.atZone(ZoneId.of("+8")).toInstant().toEpochMilli();
   gen.writeNumber(millis);
  }
 }
}
package com.xxx.config.serializers;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class StringDeserializer extends JsonDeserializer<String> {
 @Override
 public String deserialize(JsonParser p, DeserializationContext ctxt)
   throws IOException, JsonProcessingException {
  String text = p.getText();
  if ("".equals(text)) {
   return null;
  }
  return text;
 }
}
package com.xxx.config.serializers;
import java.io.IOException;
import java.util.Date;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class DateDeserializer extends JsonDeserializer<Date> {
 @Override
 public Date deserialize(JsonParser p, DeserializationContext ctxt)
   throws IOException, JsonProcessingException {
  long timestamp = p.getValueAsLong();
        if (timestamp > 0){
            return new Date(timestamp);
        }else{
            return null;
        }
 }
}
package com.xxx.config.serializers;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
 @Override
 public LocalDate deserialize(JsonParser p, DeserializationContext ctxt)
   throws IOException, JsonProcessingException {
  long timestamp = p.getValueAsLong();
        if (timestamp > 0){
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp),ZoneId.of("+8")).toLocalDate();
        }else{
            return null;
        }
 }
}
package com.xxx.config.serializers;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
 @Override
 public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt)
   throws IOException, JsonProcessingException {
  long timestamp = p.getValueAsLong();
        if (timestamp > 0){
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp),ZoneId.of("+8"));
        }else{
            return null;
        }
 }
}

Jackson统一配置类

package com.xxx.config;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.xxx.config.serializers.DateDeserializer;
import com.xxx.config.serializers.DateSerializer;
import com.xxx.config.serializers.LocalDateDeserializer;
import com.xxx.config.serializers.LocalDateSerializer;
import com.xxx.config.serializers.LocalDateTimeDeserializer;
import com.xxx.config.serializers.LocalDateTimeSerializer;
import com.xxx.config.serializers.StringDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
@Configuration
public class JacksonConfig {
 @Bean
 public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
  Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
   
   @Override
   public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
    jacksonObjectMapperBuilder
      .serializerByType(Long.TYPE, ToStringSerializer.instance)
      .serializerByType(Long.class, ToStringSerializer.instance)
      .serializerByType(Date.class, new DateSerializer())
      .serializerByType(LocalDate.class, new LocalDateSerializer())
      .serializerByType(LocalDateTime.class, new LocalDateTimeSerializer())
      .deserializerByType(String.class, new StringDeserializer())
      .deserializerByType(Date.class, new DateDeserializer())
      .deserializerByType(LocalDate.class, new LocalDateDeserializer())
      .deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer())
      .failOnEmptyBeans(false)
      .failOnUnknownProperties(false);
   }
  };
  return customizer;
 }
}

Jackson工具类

package com.xxx.util;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.TimeZone;
import com.xxx.config.serializers.StringDeserializer;
import com.xxx.config.serializers.DateDeserializer;
import com.xxx.config.serializers.DateSerializer;
import com.xxx.config.serializers.LocalDateDeserializer;
import com.xxx.config.serializers.LocalDateSerializer;
import com.xxx.config.serializers.LocalDateTimeDeserializer;
import com.xxx.config.serializers.LocalDateTimeSerializer;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class JsonUtils {
  
 private static final ObjectMapper objectMapper;
 static {
  objectMapper = new ObjectMapper();
  // 去掉默认的时间戳格式
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  // 设置为中国北京时区
  objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
  // 空值不序列化
//  objectMapper.setSerializationInclusion(Include.NON_NULL);//已过时
//  objectMapper.setDefaultPropertyInclusion(Include.NON_NULL);//新API
  // 反序列化时,属性不存在的兼容处理
  objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 
  objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  // 单引号处理
  objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
  
  JavaTimeModule javaTimeModule = new JavaTimeModule();
  javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
  javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance);
  javaTimeModule.addSerializer(Date.class, new DateSerializer());
  javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());        
        javaTimeModule.addDeserializer(String.class, new StringDeserializer());
        javaTimeModule.addDeserializer(Date.class, new DateDeserializer());
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
 }
 
 /**
  * json 转换成 Object
  *
  * @param json
  * @param clazz
  * @return
  */
 public static <T> T json2Object(String json, Class<T> clazz) {
  try {
   return objectMapper.readValue(json, clazz);
  } catch (IOException e) {
   throw new RuntimeException("解析json错误");
  }
 }
 
 @SuppressWarnings("unchecked")
 public static <T> T json2Object(String json, TypeReference<T> tr) {
  try {
   return (T)objectMapper.readValue(json, tr);
  } catch (IOException e) {
   throw new RuntimeException("解析json错误", e);
  }
 }
 
 /**
  * obj 转换成json
  *
  * @param entity
  * @return
  */
 public static <T> String object2Json(T entity) {
  try {
   return objectMapper.writeValueAsString(entity);
  } catch (IOException e) {
   throw new RuntimeException("转换json错误");
  }
 }
 
 /**
  * obj对象 转换成树型JSON
  *
  * @param obj
  * @return
  */
 public static JsonNode object2TreeJson(Object obj) {
  try {
   return objectMapper.valueToTree(obj);
  } catch (Exception e) {
   throw new RuntimeException("转换json错误");
  }
 }
 
   /**
     * 解码json串成对象
     *
     * @param <T>
     * @param json
     * @param valueType
     * @return T
     */
    @SuppressWarnings("unchecked")
    public static <T> T decode(String json, Class<?> valueType) {
        try {
            return (T) objectMapper.readValue(json, valueType);
        } catch (Exception e) {
            throw new RuntimeException(json, e);
        }
    }
 /**
     * 解码json串成JsonNode
     * @param json
     * @return
     */
    public static JsonNode readTree(String json) {
     try {
   return objectMapper.readTree(json);
  } catch (Exception e) {
   throw new RuntimeException(json, e);
  }
    }    
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • springboot多文件上传代码实例及解析

    springboot多文件上传代码实例及解析

    这篇文章主要介绍了springboot多文件上传代码实例及解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Java中的延迟队列DelayQueue详细解析

    Java中的延迟队列DelayQueue详细解析

    这篇文章主要介绍了Java中的延迟队列DelayQueue详细解析,JDK自身支持延迟队列的数据结构,其实类:java.util.concurrent.DelayQueue,<BR>我们通过阅读源码的方式理解该延迟队列类的实现过程,需要的朋友可以参考下
    2023-12-12
  • IntelliJ IDEA(2020.2)的下载、安装步骤详细教程

    IntelliJ IDEA(2020.2)的下载、安装步骤详细教程

    这篇文章主要介绍了IntelliJ IDEA(2020.2)的下载、安装步骤详细教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • JDBC查询Map转对象实现过程详解

    JDBC查询Map转对象实现过程详解

    这篇文章主要介绍了JDBC查询Map转对象实现过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • java根据不同的参数调用不同的实现类操作

    java根据不同的参数调用不同的实现类操作

    这篇文章主要介绍了java根据不同的参数调用不同的实现类操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Java必备知识之位运算及常见进制解读

    Java必备知识之位运算及常见进制解读

    从现代计算机中所有的数据二进制的形式存储在设备中。即 0、1 两种状态,计算机对二进制数据进行的运算(+、-、*、/)都是叫位运算,即将符号位共同参与运算的运算
    2021-10-10
  • Mybatis 传输List的实现代码

    Mybatis 传输List的实现代码

    本文通过实例代码给大家介绍了mybatis传输list的实现代码,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-09-09
  • Spring DATA JPA 中findAll 进行OrderBy方式

    Spring DATA JPA 中findAll 进行OrderBy方式

    这篇文章主要介绍了Spring DATA JPA 中findAll 进行OrderBy方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • Java用split分割含一个或多个空格的字符串案例

    Java用split分割含一个或多个空格的字符串案例

    这篇文章主要介绍了Java用split分割含一个或多个空格的字符串案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来过来看看吧
    2020-09-09
  • MyBatis传入参数为List对象的实现

    MyBatis传入参数为List对象的实现

    这篇文章主要介绍了MyBatis传入参数为List对象的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03

最新评论