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);
    }
}

解决后再查看:

相关推荐
阿蒙Amon14 分钟前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
daidaidaiyu19 分钟前
Spring IOC 源码学习 一文学习完整的加载流程
java·spring
2***d88532 分钟前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端
五阿哥永琪33 分钟前
Spring中的定时任务怎么用?
java·后端·spring
追逐时光者34 分钟前
C#/.NET/.NET Core技术前沿周刊 | 第 65 期(2026年1.1-1.11)
后端·.net
计算机毕设VX:Fegn089537 分钟前
计算机毕业设计|基于springboot + vue小型房屋租赁系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
gelald44 分钟前
AQS 工具之 CountDownLatch 与 CyclicBarry 学习笔记
java·后端·源码阅读
且去填词1 小时前
Go 语言的“反叛”——为什么少即是多?
开发语言·后端·面试·go
better_liang1 小时前
每日Java面试场景题知识点之-XXL-JOB分布式任务调度实践
java·spring boot·xxl-job·分布式任务调度·企业级开发
会游泳的石头1 小时前
一行注解防死循环:MyBatis 递归深度限制(无需 level 字段)
java·mybatis