SpringBoot解决LocalDateTime返回数据为数组问题

现象:

在SpringBoot项目中,接口返回的数据出现LocalDateTime对象被转换成了数组

原因分析:

默认序列化情况下会使用SerializationFeature.WRITE_DATES_AS_TIMESTAMPS。使用这个解析时就会打印出数组。

解决方法:

在配置类中加入一行配置,解决问题

复制代码
package com.demo.config

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
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.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

@Configuration // 配置类
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
        // 不显示为null的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        // 放到第一个
        converters.add(0, jackson2HttpMessageConverter);
    }
}

解决后再查看:

相关推荐
凤山老林1 分钟前
RocketMQ 5.0 实战避坑与调优:事务、延迟、轨迹及高可用落地指南
spring boot·rocketmq
君顾12 分钟前
本地电竞服务交易系统架构设计与实战:从同城服务撮合到订单履约
java·开发语言·电竞
TanYYF4 分钟前
Spring Boot 2 与 Spring Boot 3 自动装配的区别及 Boot 3 装配流程详解
spring boot
小刘在重生~4 分钟前
十六(3)、《集合扩充》CopyOnWriteArrayList 超详细解析(线程安全集合)
java·笔记·面试·职场和发展
逆境不可逃5 分钟前
Pi Agent 学习笔记:对话怎样保存、分支与恢复
java
盗_心i8 分钟前
OCPP 1.6-J 配置管理手册:GetConfiguration / ChangeConfiguration 与标准配置键
后端
传奇开心果编程11 分钟前
【Go入门练中学】第1课:从零开始
后端·学习·golang
RuoyiOffice12 分钟前
SpringBoot3+OnlyOffice 自动保存版本:定时回存、间隔合并与 50 版上限怎么配
spring boot·在线文档·onlyoffice·版本管理·spring boot 3·自动保存·ruoyi office
isfox14 分钟前
Python 的 @classmethod 和 @staticmethod:什么时候用哪个,一次说清楚
后端
huaweichenai20 分钟前
spring boot使用hutool实现调用外部接口
java·spring boot