@JsonFormat失效,被jackson自定义配置覆盖

2024-01-25 21:44

本文主要是介绍@JsonFormat失效,被jackson自定义配置覆盖,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

jackson配置类

我的jackson配置类如下,其中serializerByType(LocalDateTime.class, new LocalDateTimeSerializer()) 覆盖了@JsonFormat注解

@Configuration
public class JacksonConfiguration {public static final DateTimeFormatter optionalDateTimePattern =(new DateTimeFormatterBuilder()).appendValue(ChronoField.YEAR, 4).appendPattern("[-][/]MM[-][/]dd['T'][ ]HH[:]mm[:][ss][,SSS][.SSS]").toFormatter();;static final ZoneOffset zoneOffset = OffsetDateTime.now(ZoneId.systemDefault()).getOffset();public JacksonConfiguration() {}/*** 配置和创建ObjectMapper对象*/public static Jackson2ObjectMapperBuilder createJackson2ObjectMapperBuilder() {Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();return customizeBuilder(builder).serializerByType(LocalDateTime.class, new LocalDateTimeSerializer());}@Beanpublic Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {return (builder) -> {// serializerByType(LocalDateTime.class, new LocalDateTimeSerializer()) 覆盖了@JsonFormat注解customizeBuilder(builder).serializerByType(LocalDateTime.class, new LocalDateTimeSerializer());};}private static Jackson2ObjectMapperBuilder customizeBuilder(Jackson2ObjectMapperBuilder builder) {builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer())// 将日期时间序列化为时间戳(以毫秒表示),而不是默认的日期时间字符串格式,如果已经设置了serializerByType则会失效.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)// 允许将单个值解析为数组。这意味着如果 JSON 中的某个属性期望是数组类型,但实际上只有一个值,那么它也会被解析为数组。.featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)// 解开包装在单个值数组中的值。这意味着如果 JSON 中的某个属性被包装在一个只有一个元素的数组中,那么它会被解包成单个值。.featuresToEnable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);return builder;}public static final class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {public LocalDateTimeDeserializer() {}public LocalDateTime deserialize(JsonParser p, DeserializationContext context) throws IOException {// 时间戳格式if (StringUtils.isNumeric(p.getValueAsString())) {long timestamp = Long.parseLong(p.getValueAsString());// 带毫秒if (p.getValueAsString().length() == 13) {return Instant.ofEpochMilli(timestamp).atZone(JacksonConfiguration.zoneOffset).toLocalDateTime();}// 不带毫秒else {return Instant.ofEpochSecond(timestamp).atZone(JacksonConfiguration.zoneOffset).toLocalDateTime();}} else {// 2023-09-08 16:12:25 或 2023-09-08T16:12:25 或 2023-09-08 16:12:25.456 格式String dateTimeString = p.getValueAsString();if (StringUtils.isNotEmpty(dateTimeString)) {return LocalDateTime.parse(dateTimeString, optionalDateTimePattern);} else {return null;}}}}public static final class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {public LocalDateTimeSerializer() {}public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)throws IOException {gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());}}
}

实体类

当我在LocalDateTime类型的属性上使用@JsonForMat失效

public class TestDTO {@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss", timezone = "GMT+8")private LocalDateTime localDateTime;public LocalDateTime getLocalDateTime() {return localDateTime;}public void setLocalDateTime(LocalDateTime localDateTime) {this.localDateTime = localDateTime;}@Overridepublic String toString() {return "TestDTO{" + "localDateTime=" + localDateTime + '}';}
}

接口

调用接口的返回值是时间戳,而不是 yyyy/MM/dd HH:mm:ss

@PostMapping("/test7")public TestDTO test7() {TestDTO testDTO = new TestDTO();testDTO.setLocalDateTime(LocalDateTime.now());return testDTO;}

返回值:

{"localDateTime": 1706086696221
}

一种解决方法

改用 @JsonSerialize 注解

@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime localDateTime;

在外面定义一个LocalDateTimeSerializer,在serialize方法中定义要输出的格式

package com.xjhqre.config;import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {gen.writeString(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(value));}
}

这篇关于@JsonFormat失效,被jackson自定义配置覆盖的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/644705

相关文章

史上最全nginx详细参数配置

《史上最全nginx详细参数配置》Nginx是一个轻量级高性能的HTTP和反向代理服务器,同时也是一个通用代理服务器(TCP/UDP/IMAP/POP3/SMTP),最初由俄罗斯人IgorSyso... 目录基本命令默认配置搭建站点根据文件类型设置过期时间禁止文件缓存防盗链静态文件压缩指定定错误页面跨域问题

nginx负载均衡及详细配置方法

《nginx负载均衡及详细配置方法》Nginx作为一种高效的Web服务器和反向代理服务器,广泛应用于网站的负载均衡中,:本文主要介绍nginx负载均衡及详细配置,需要的朋友可以参考下... 目录一、 nginx负载均衡策略1.1 基本负载均衡策略1.2 第三方策略1.3 策略对比二、 nginx配置2.1

Android开发环境配置避坑指南

《Android开发环境配置避坑指南》本文主要介绍了Android开发环境配置过程中遇到的问题及解决方案,包括VPN注意事项、工具版本统一、Gerrit邮箱配置、Git拉取和提交代码、MergevsR... 目录网络环境:VPN 注意事项工具版本统一:android Studio & JDKGerrit的邮

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

如何为Yarn配置国内源的详细教程

《如何为Yarn配置国内源的详细教程》在使用Yarn进行项目开发时,由于网络原因,直接使用官方源可能会导致下载速度慢或连接失败,配置国内源可以显著提高包的下载速度和稳定性,本文将详细介绍如何为Yarn... 目录一、查询当前使用的镜像源二、设置国内源1. 设置为淘宝镜像源2. 设置为其他国内源三、还原为官方

CentOS7更改默认SSH端口与配置指南

《CentOS7更改默认SSH端口与配置指南》SSH是Linux服务器远程管理的核心工具,其默认监听端口为22,由于端口22众所周知,这也使得服务器容易受到自动化扫描和暴力破解攻击,本文将系统性地介绍... 目录引言为什么要更改 SSH 默认端口?步骤详解:如何更改 Centos 7 的 SSH 默认端口1

Maven的使用和配置国内源的保姆级教程

《Maven的使用和配置国内源的保姆级教程》Maven是⼀个项目管理工具,基于POM(ProjectObjectModel,项目对象模型)的概念,Maven可以通过一小段描述信息来管理项目的构建,报告... 目录1. 什么是Maven?2.创建⼀个Maven项目3.Maven 核心功能4.使用Maven H