【Spring Boot】如何自定义序列化以及反序列器

在我们使用默认的消息转换器,将java的Long类型通过json数据传输到前端JS时,会导致Long类型的精度丢失,这是因为JS处理Long类型数字只能精确到前16位,所以我们可以采用自定义序列化方式将Long类型数据统一转为String字符串,然后再传输到前端即可解决问题。

  1. 定义jackson的对象映射器
    1.

    java 复制代码
    package com.app.studypro.common;
    
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.module.SimpleModule;
    import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
    
    import java.math.BigInteger;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    
    import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
    
    /**
     * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
     * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
     * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
     *
     * @author Administrator
     */
    public class JacksonObjectMapper extends ObjectMapper {
    
        /**
         * LocalDate类型
         */
        public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
        /**
         * LocalDateTime类型
         */
        public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        /**
         * LocalTime类型
         */
        public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    
        @SuppressWarnings("ResultOfMethodCallIgnored")
        public JacksonObjectMapper() {
            super();
            // 收到未知属性时不报异常
            this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
            // 反序列化时,属性不存在的兼容处理
            this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    
            // 配置注册序列化程序和反序列化程序的自定义信息
            SimpleModule simpleModule = new SimpleModule()
                    // 时间的反序列化
                    .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                    .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                    .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
    
                    // BigInteger的序列化
                    .addSerializer(BigInteger.class, ToStringSerializer.instance)
                    // Long的序列化
                    .addSerializer(Long.class, ToStringSerializer.instance)
                    // 时间的序列化
                    .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                    .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                    .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
    
            // 注册功能模块,以此可以添加自定义序列化器和反序列化器
            this.registerModule(simpleModule);
        }
    
    }
  2. 在Spring mvc的消息转换器中添加jackson的对象映射器
    1.

    java 复制代码
    package com.app.studypro.config;
    
    import com.app.studypro.common.JacksonObjectMapper;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    
    import java.util.List;
    
    /**
     * Spring mvc的配置设定
     *
     * @author Administrator
     */
    @Slf4j
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurationSupport {
    
        @Override
        protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
            log.info("扩展消息转换器,自定义添加 {} 消息转化器到spring mvc中", JacksonObjectMapper.class);
            // 创建消息转换器对象
            MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
            // 设置对象转换器,底层使用Jackson将Java对象转为json
            messageConverter.setObjectMapper(new JacksonObjectMapper());
            // 将上面的消息转换器对象追加到mvc框架的转换器集合中,将其放在转换器集合的首个位置
            converters.add(0, messageConverter);
        }
    
    }
相关推荐
MateCloud微服务27 分钟前
懂你所需,利爪随行:MateClaw 正式开源,补齐 Java 生态的 AI Agent 拼图
spring boot·aigc·javaagent·aiagent·openclaw·mateclaw·javaclaw
emmjng36928 分钟前
使用飞算JavaAI实现在线图书借阅平台
java
CoderYanger31 分钟前
14届蓝桥杯省赛Java A 组Q1~Q3
java·开发语言·线性代数·算法·职场和发展·蓝桥杯
钮钴禄·爱因斯晨32 分钟前
他到底喜欢我吗?赛博塔罗Java+前端实现,一键解答!
java·开发语言·前端·javascript·css·html
词元Max34 分钟前
Java 转 AI Agent 开发学习路线(2026年3月最新版)
java·人工智能·学习
亚历克斯神34 分钟前
Java 云原生开发最佳实践:构建现代化应用
java·spring·微服务
布说在见34 分钟前
企业级 Java 登录注册系统构建指南(附核心代码与配置)
java·开发语言
是宇写的啊34 分钟前
SpringBoot配置文件
java·spring boot·spring
草莓熊Lotso35 分钟前
一文读懂 Java 主流编译器:特性、场景与选择指南
java·开发语言·经验分享
Y001112361 小时前
Maven
java·maven