@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

相关文章

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Goland debug失效详细解决步骤(合集)

《Golanddebug失效详细解决步骤(合集)》今天用Goland开发时,打断点,以debug方式运行,发现程序并没有断住,程序跳过了断点,直接运行结束,网上搜寻了大量文章,最后得以解决,特此在这... 目录Bug:Goland debug失效详细解决步骤【合集】情况一:Go或Goland架构不对情况二:

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的

Spring Boot整合log4j2日志配置的详细教程

《SpringBoot整合log4j2日志配置的详细教程》:本文主要介绍SpringBoot项目中整合Log4j2日志框架的步骤和配置,包括常用日志框架的比较、配置参数介绍、Log4j2配置详解... 目录前言一、常用日志框架二、配置参数介绍1. 日志级别2. 输出形式3. 日志格式3.1 PatternL

配置springboot项目动静分离打包分离lib方式

《配置springboot项目动静分离打包分离lib方式》本文介绍了如何将SpringBoot工程中的静态资源和配置文件分离出来,以减少jar包大小,方便修改配置文件,通过在jar包同级目录创建co... 目录前言1、分离配置文件原理2、pom文件配置3、使用package命令打包4、总结前言默认情况下,

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

VScode连接远程Linux服务器环境配置图文教程

《VScode连接远程Linux服务器环境配置图文教程》:本文主要介绍如何安装和配置VSCode,包括安装步骤、环境配置(如汉化包、远程SSH连接)、语言包安装(如C/C++插件)等,文中给出了详... 目录一、安装vscode二、环境配置1.中文汉化包2.安装remote-ssh,用于远程连接2.1安装2

mysql外键创建不成功/失效如何处理

《mysql外键创建不成功/失效如何处理》文章介绍了在MySQL5.5.40版本中,创建带有外键约束的`stu`和`grade`表时遇到的问题,发现`grade`表的`id`字段没有随着`studen... 当前mysql版本:SELECT VERSION();结果为:5.5.40。在复习mysql外键约

Redis多种内存淘汰策略及配置技巧分享

《Redis多种内存淘汰策略及配置技巧分享》本文介绍了Redis内存满时的淘汰机制,包括内存淘汰机制的概念,Redis提供的8种淘汰策略(如noeviction、volatile-lru等)及其适用场... 目录前言一、什么是 Redis 的内存淘汰机制?二、Redis 内存淘汰策略1. pythonnoe

windos server2022的配置故障转移服务的图文教程

《windosserver2022的配置故障转移服务的图文教程》本文主要介绍了windosserver2022的配置故障转移服务的图文教程,以确保服务和应用程序的连续性和可用性,文中通过图文介绍的非... 目录准备环境:步骤故障转移群集是 Windows Server 2022 中提供的一种功能,用于在多个