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

自定义反序列化类将LocalDate时间格式转为 LocalDateTime

从前端接收数据反序列化成类,如果时间格式不一致可能会反序列化失败

public class StorageDTO implements Serializable {private static final long serialVersionUID = 1L;......//实体类中格式为@JsonFormat(pattern = "yyyy-MM-dd")@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)@ApiModelProperty("产生时间")private LocalDateTime generateTime;}
//自定义反序列化类
package com......config;import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;public class CustomLocalDateTimeDeserializer extends LocalDateTimeDeserializer {private static final long serialVersionUID = 1L;private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;private CustomLocalDateTimeDeserializer() {super(DEFAULT_FORMATTER);}public CustomLocalDateTimeDeserializer(DateTimeFormatter formatter) {super(formatter);}@Overrideprotected LocalDateTimeDeserializer withDateFormat(DateTimeFormatter formatter) {return new CustomLocalDateTimeDeserializer(formatter);}@Overridepublic LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {LocalDate localDate = new LocalDateDeserializer(_formatter).deserialize(p, ctxt);LocalDateTime localDateTime = localDate.atStartOfDay();return localDateTime;}
}

后端统一返回格式化后的日期

package com.......config;import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
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 com.......filters.ReHttpServletRequestFilter;
import com.......interceptor.DeviceHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.TimeZone;/*** 通用配置** @author balance*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";//默认日期时间格式public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";//默认日期格式public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";//默认时间格式@Autowiredprivate DeviceHandlerInterceptor deviceHandlerInterceptor;/*** 自定义拦截规则*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(deviceHandlerInterceptor).addPathPatterns("/test/**").excludePathPatterns("/testPage/**");//设备端请求拦截器}@Beanpublic FilterRegistrationBean httpServletRequestReplacedRegistration() {FilterRegistrationBean registration = new FilterRegistrationBean();registration.setFilter(new ReHttpServletRequestFilter());registration.addUrlPatterns("/*");registration.addInitParameter("paramName", "paramValue");registration.setName("reHttpServletRequestFilter");registration.setOrder(1);return registration;}/*** 跨域配置*/@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);// 设置访问源地址config.addAllowedOriginPattern("*");// 设置访问源请求头config.addAllowedHeader("*");// 设置访问源请求方法config.addAllowedMethod("*");// 有效期 1800秒config.setMaxAge(1800L);// 添加映射路径,拦截一切请求UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);// 返回新的CorsFilterreturn new CorsFilter(source);}/*** 配置全局localDateTime输出格式* @return*/@Beanpublic MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();ObjectMapper objectMapper = new ObjectMapper();objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 忽略json字符串中不识别的属性objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);// 忽略无法转换的对象objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); // PrettyPrinter 格式化输出objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);// NULL不参与序列化objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));// 指定时区objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT)); // 日期类型字符串处理// java8日期处理JavaTimeModule javaTimeModule = new JavaTimeModule();//序列化规则javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));//反序列化规则javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));objectMapper.registerModule(javaTimeModule);mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);return mappingJackson2HttpMessageConverter;}@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(mappingJackson2HttpMessageConverter());}}

相关文章:

自定义反序列化类将LocalDate时间格式转为 LocalDateTime

从前端接收数据反序列化成类,如果时间格式不一致可能会反序列化失败 public class StorageDTO implements Serializable {private static final long serialVersionUID 1L;......//实体类中格式为JsonFormat(pattern "yyyy-MM-dd")JsonDeserialize(using CustomL…...

MySQL JSON_TABLE() 函数

JSON_TABLE()函数从一个指定的JSON文档中提取数据并返回一个具有指定列的关系表。 应用&#xff1a;数据库字段以JSON 存储后&#xff0c;实际应用需要对其中一个字段进行查询 语法 JSON_TABLE(json,path COLUMNS(column[,column[,...]]))column:name参数 json必需的。一个 …...

【MATLAB第80期】基于MATLAB的结构核岭回归SKRR多输入单输出回归预测及分类预测模型

【MATLAB第80期】基于MATLAB的结构核岭回归SKRR多输入单输出回归预测及分类预测模型 SKRR这是Gustau Camps-Valls等人在“用深度结构核回归检索物理参数”中提出的结构核岭回归&#xff08;SKRR&#xff09;方法。 参考文献&#xff1a; Camps-Valls,Retrieval of Physical Pa…...

Qt消息对话框的使用

本文介绍Qt消息对话框的使用。 QMessageBox类是Qt编程中常用到的一个类&#xff0c;主要用来进行一些简单的消息提示&#xff0c;比如&#xff1a;问题对话框&#xff0c;信息对话框等&#xff0c;这些对话框都属于QMessageBox类的静态方法&#xff0c;使用起来比较简单&#…...

spring的Ioc、DI以及Bean的理解

文章目录 什么是Ioc&#xff1f;Spring和这有什么关系Spring是怎么做的&#xff1f;如果service层对dao层有依赖该怎么办&#xff1f;什么叫做依赖注入Spring这样做的目的是什么参考文献 什么是Ioc&#xff1f; Ioc(Inversion of Control) 控制反转&#xff0c;就是使用对象时…...

倒计时 天时分秒

shijian() {const EndTIME new Date(开始时间变量); // 截止时间const NowTime new Date(); // 开始时间const usedTime EndTIME - NowTime; // 相差的毫秒数const days Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数const leavel usedTime % (24 * 3600 * 1…...

Spring篇---第六篇

系列文章目录 文章目录 系列文章目录一、Spring 框架中的单例 Bean 是线程安全的么?二、Spring 是怎么解决循环依赖的?三、说说事务的隔离级别一、Spring 框架中的单例 Bean 是线程安全的么? Spring 框架并没有对单例 Bean 进行任何多线程的封装处理。 关于单例 Bean 的线程…...

【unity小技巧】适用于任何 2d 游戏的钥匙门系统和buff系统——UnityEvent的使用

文章目录 每篇一句前言开启配置门的开启动画代码调用&#xff0c;控制开启门动画 新增CollisionDetector 脚本&#xff0c;使用UnityEvent &#xff0c;控制钥匙和门的绑定多把钥匙控制多个门一把钥匙控制多个门 BUFF系统扩展参考源码完结 每篇一句 人总是害怕去追求自己最重要…...

爬虫ip如何加入到代码里实现自动化数据抓取

以下是一个使用HTTP:Tiny和www.weibo.com的音频爬虫程序的示例。这个示例使用了https://www.duoip.cn/get_proxy来获取爬虫IP。请注意&#xff0c;这个示例可能需要根据你的实际需求进行调整。 #!/usr/bin/perluse strict; use warnings; use HTTP::Tiny; use LWP::UserAgent; …...

在win10上安装配置Hadoop的环境变量

一、背景 在windows10系统中运行seatunnel 二、安装部署 2.1. 下载 Hadoop包 从 Apache Hadoop 官网下载最新版本的 Hadoop&#xff0c;版本号保持与服务端的Hadoop版本一致。 https://hadoop.apache.org/releases.htmlIndex of /apache/hadoop/core/hadoop-3.2.3/ 2.2. 解…...

MAX插件CG Magic怎么云渲染?操作方法已整起!

小编这里会收到不少网友的反馈是关于3ds max插件CG Magic怎么云渲染&#xff1f; 3d max的这款插件CG MAGIC的出现就是为了设计师使用过程中&#xff0c;可以省时又省心的完成工作。 同时&#xff0c;大家要了键下&#xff0c;现阶段CG MAGIC有18个板块&#xff0c;118个模块…...

尝试使用jmeter-maven-plugin

前提准备 1、maven项目 2、已安装JMeter、Jenkins、maven、jdk 环境要求&#xff1a; jmeter>5.6.2 maven >3.9 jdk>1.8 Jenkins ? 备注&#xff1a;jmeter-maven-plugin 无需下载&#xff0c;可查阅相关地址&#xff1a;GitHub - jmeter-maven-plugin/jmete…...

navigator.userAgent.toLowerCase区分设备,浏览器

navigator.userAgent.toLowerCase区分设备&#xff0c;浏览器 navigator.userAgent.toLowerCase(&#xff09;区分设备是pc还是移动端在确认是移动端的基础上&#xff0c;判断是Android、ipad、iphone内置的浏览器&#xff0c;比如新浪微博、腾讯QQ&#xff08;非QQ浏览器&…...

防火墙操作:开放端口ICMP时间戳请求漏洞修复

响应ICMP时间戳请求漏洞修复 firewall-cmd --permanent --zonepublic --add-icmp-blocktimestamp-reply firewall-cmd --permanent --zonepublic --add-icmp-blocktimestamp-request firewall-cmd --reload --防火墙状态 systemctl status firewalld --打开防火墙 systemctl …...

MySQL配置环境变量和启动登录

如果不配置环境变量&#xff0c;每次登录 MySQL 服务器时就必须进入到 MySQL 的 bin 目录下&#xff0c;也就是输入“cd C:\Program Files\MySQL\MySQL Server 5.7\bin”命令后&#xff0c;才能使用 MySQL 等其它命令工具&#xff0c;这样比较麻烦。配置环境变量以后就可以在任…...

救济金发放(The Dole Queue, UVa 133)rust解法

n(n<20)个人站成一圈&#xff0c;逆时针编号为1&#xff5e;n。有两个官员&#xff0c;A从1开始逆时针数&#xff0c;B从n开始顺时针数。在每一轮中&#xff0c;官员A数k个就停下来&#xff0c;官员B数m个就停下来&#xff08;注意有可能两个官员停在同一个人上&#xff09;…...

oracle实验四

创建文件 &#xff08;1&#xff09;为 ORCL 数据库创建一个名为 BOOKTBS1 的永久性表空间&#xff0c;数据文件为’d:\bt01.dbf’ &#xff0c;大小为100M&#xff0c;区采用自动扩展方式&#xff08;即自动分配&#xff09;&#xff0c; 段采用自动管理方式&#xff1b; &am…...

数据结构-堆排序Java实现

目录 一、引言二、算法步骤三、原理演示步骤1: 构建最大堆步骤2: 交换和堆化步骤3: 排序完成 四、代码实战五、结论 一、引言 堆排序是一种利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构&#xff0c;并同时满足堆积的性质&#xff1a;即子结点的键值或…...

C#进阶——反射(Reflection)

定义&#xff1a;反射指的是在运行时动态地获取、检查和操作程序中的类型信息&#xff0c;而在我们的Unity中反射允许开发者在运行时通过代码来访问和修改对象的属性、方法和字段&#xff0c;而不需要提前知道这些成员的具体信息。 举一个例子&#xff0c;我们使用反射在运行的…...

Oracle 运维篇+应用容器数据库的install、upgrade、patch、uninstall

★ 知识点 ※ DEFAULT_SHARING参数的取值 METADATA: 元数据链接共享数据库对象的元数据&#xff0c;但其数据对于每个容器是唯一的。这些数据库对象被称为元数据链接的应用程序公共对象。此设置为默认设置。DATA: 数据链接共享数据库对象&#xff0c;其数据对于应用程序容器中…...

Java 语言特性(面试系列2)

一、SQL 基础 1. 复杂查询 &#xff08;1&#xff09;连接查询&#xff08;JOIN&#xff09; 内连接&#xff08;INNER JOIN&#xff09;&#xff1a;返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

在rocky linux 9.5上在线安装 docker

前面是指南&#xff0c;后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

镜像里切换为普通用户

如果你登录远程虚拟机默认就是 root 用户&#xff0c;但你不希望用 root 权限运行 ns-3&#xff08;这是对的&#xff0c;ns3 工具会拒绝 root&#xff09;&#xff0c;你可以按以下方法创建一个 非 root 用户账号 并切换到它运行 ns-3。 一次性解决方案&#xff1a;创建非 roo…...

【Go】3、Go语言进阶与依赖管理

前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课&#xff0c;做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程&#xff0c;它的核心机制是 Goroutine 协程、Channel 通道&#xff0c;并基于CSP&#xff08;Communicating Sequential Processes&#xff0…...

学习STC51单片机31(芯片为STC89C52RCRC)OLED显示屏1

每日一言 生活的美好&#xff0c;总是藏在那些你咬牙坚持的日子里。 硬件&#xff1a;OLED 以后要用到OLED的时候找到这个文件 OLED的设备地址 SSD1306"SSD" 是品牌缩写&#xff0c;"1306" 是产品编号。 驱动 OLED 屏幕的 IIC 总线数据传输格式 示意图 …...

【配置 YOLOX 用于按目录分类的图片数据集】

现在的图标点选越来越多&#xff0c;如何一步解决&#xff0c;采用 YOLOX 目标检测模式则可以轻松解决 要在 YOLOX 中使用按目录分类的图片数据集&#xff08;每个目录代表一个类别&#xff0c;目录下是该类别的所有图片&#xff09;&#xff0c;你需要进行以下配置步骤&#x…...

CMake 从 GitHub 下载第三方库并使用

有时我们希望直接使用 GitHub 上的开源库,而不想手动下载、编译和安装。 可以利用 CMake 提供的 FetchContent 模块来实现自动下载、构建和链接第三方库。 FetchContent 命令官方文档✅ 示例代码 我们将以 fmt 这个流行的格式化库为例,演示如何: 使用 FetchContent 从 GitH…...

JavaScript基础-API 和 Web API

在学习JavaScript的过程中&#xff0c;理解API&#xff08;应用程序接口&#xff09;和Web API的概念及其应用是非常重要的。这些工具极大地扩展了JavaScript的功能&#xff0c;使得开发者能够创建出功能丰富、交互性强的Web应用程序。本文将深入探讨JavaScript中的API与Web AP…...

AI+无人机如何守护濒危物种?YOLOv8实现95%精准识别

【导读】 野生动物监测在理解和保护生态系统中发挥着至关重要的作用。然而&#xff0c;传统的野生动物观察方法往往耗时耗力、成本高昂且范围有限。无人机的出现为野生动物监测提供了有前景的替代方案&#xff0c;能够实现大范围覆盖并远程采集数据。尽管具备这些优势&#xf…...