当前位置: 首页 > java >正文

SpringBoot WebMvcConfigurer使用Jackson统一序列化格式化输出

常用json数据格式化有:
1、Long转String防止JS精度丢失
2、时间日期类型的统一格式化

可以使用注解实现json数据格式化:

    /*** 主键 将long使用String序列化*/@JsonSerialize(using = ToStringSerializer.class)@JSONField(serializeUsing = ToStringSerializer.class)private Long id;/*** 时间 日期类格式 注解*/@JSONField(format = "yyyy-MM-dd HH:mm:ss")@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private LocalDateTime createTime;

使用注解方式非常繁重,直接在WebMvcConfigurer统一配置实现接口数据响应的格式化输出。

springboot 统一格式化输出简单实现方式;
1、Jackson中ObjectMapper序列化配置

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 lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;/*** 全局 jackson 序列化配置** @author Yang douya* @date 2025/5/29 9:13*/
@Slf4j
@Configuration
public class JacksonConfig {public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";//    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";/*** 创建Jackson对象映射器** @param builder Jackson对象映射器构建器* @return ObjectMapper*/@Primary@Bean("objectMapper")public ObjectMapper getJacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {ObjectMapper objectMapper = builder.createXmlMapper(false).build();//序列换成json时,将所有的long变成string.因为js中得数字类型不能包含所有的java long值,超过16位后会出现精度丢失SimpleModule simpleModule = new SimpleModule();// 字符传转为StringsimpleModule.addSerializer(Long.class, ToStringSerializer.instance);simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);// 时间格式化simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));// 反序列化simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));simpleModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));simpleModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));objectMapper.registerModule(simpleModule);//反序列化的时候如果多了其他属性,不抛出异常objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//日期格式处理objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT));return objectMapper;}
}

2、统一响应格式化输出


/*** 系统拦截器及资源配置** @author helloWorld* <p>* 2018年10月20日*/
@EnableWebMvc
@Configuration
@RequiredArgsConstructor
public class WebMvcConfigurerAdapter implements WebMvcConfigurer {private final ObjectMapper objectMapper;/*** Jackson的全局序列化方式* <p>* long 转为 string* LocalData 格式化** @param converters*/@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();converter.setObjectMapper(objectMapper);converters.add(0, converter);converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));}
}

通过WebMvcConfigurer配置接口响应json数据的统一格式化。

http://www.xdnf.cn/news/9941.html

相关文章:

  • DDP与FSDP:分布式训练技术全解析
  • python常用库-pandas、Hugging Face的datasets库(大模型之JSONL(JSON Lines))
  • EasyRTC嵌入式音视频通信SDK助力1v1实时音视频通话全场景应用
  • 图解gpt之Transformer架构与设计原理
  • ONNX模型的动态和静态量化
  • 2024 CKA模拟系统制作 | Step-By-Step | 17、题目搭建-排查故障节点
  • 因泰立科技:镭眸T51激光雷达,打造智能门控新生态
  • 立控信息智能装备柜:科技赋能军队装备管理现代化
  • WindowServer2022下docker方式安装dify步骤
  • 大厂前端研发岗位设计的30道Webpack面试题及解析
  • CAD多边形密堆积2D插件
  • SpringBoot+Vue+微信小程序校园自助打印系统
  • Spring Boot 基础知识全面解析:快速构建企业级应用的核心指南
  • 用Git管理你的服务器配置文件与自动化脚本:版本控制、变更追溯、团队协作与安全回滚的运维之道
  • 服务器Docker容器创建与VScode远程连接SSH使用
  • quasar electron mode如何打包无边框桌面应用程序
  • 从零到一:我的技术博客导航(持续更新)
  • 基于开源链动2+1模式AI智能名片S2B2C商城小程序的企业组织生态化重构研究
  • 展会聚焦丨漫途科技亮相2025西北水务博览会!
  • AI生态警报:MCP协议风险与应对指南(中)——MCP Server运行时安全​​
  • 循环神经网络(RNN)全面教程:从原理到实践
  • 神经网络-Day40
  • 目标检测学习
  • Day 40
  • 一篇文章玩转CAP原理
  • methods的实现原理
  • 熵最小化Entropy Minimization (一): 基本认识
  • 解析楼宇自控系统:分布式结构的核心特点与优势展现
  • Visual studio 中.sln/.vcxproj/.vcxproj.filters和.vcxproj.user文件的作用
  • SAP Business ByDesign:无锡哲讯科技赋能中大型企业云端数字化转型