LocalDateTime去掉T
最近在使用阿里巴巴的fastjson反序列化对象的时候,对象里面时间格式属性总是会多了一个T
2021-1-09T18:29:09.097
这个T是啥国际标准,但是我们的前端又不需要这个T,所以就要想办法去掉T。
先看代码
1、添加 LocalDateTimeSerializerConfig ,这个照搬过去就行了
1 package com.dt.cloud.config; 2 3 import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; 4 import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 import java.time.LocalDateTime; 8 import java.time.format.DateTimeFormatter; 9 10 /** 11 * @Description: 去掉LocalDateTime带T的问题 12 * @author: Zhang Chonghu 13 * @Date: 2021/1/27 9:51 14 * @Copyright: Xi'an Dian Tong Software Co., Ltd. All Rights Reserved. 15 * @Version 1.0 16 */ 17 @Configuration 18 public class LocalDateTimeSerializerConfig { 19 @org.springframework.beans.factory.annotation.Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") 20 private String pattern; 21 @Bean 22 public LocalDateTimeSerializer localDateTimeDeserializer() { 23 return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); 24 } 25 @Bean 26 public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { 27 return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); 28 } 29 30 }
在给小白们看看这个目录,我们项目是有个config包专门管理这些config配置类的
2、做完配置,就要做一些代码的操作了
1 @JSONField(name="CreateTime") 2 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 3 private LocalDateTime createTime; 4 5 @JSONField(name="CreateBy") 6 private Integer createBy; 7 8 @JSONField(name="ChangeTime") 9 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 10 private LocalDateTime changeTime;
注意,我这两个时间属性是在Queue实体类中的,这里就贴这两个属性的代码出来。这里要做的就是加上@JsonFormat,上图
3、重点来了,注意看,我是先重数据库中查询出queue这个对象,在利用阿里巴巴直接序列化这个queue对象
这里要说明的是,因为业务需要,我要把整个对象返回,所以要序列化这个对象,再序列化那两个时间属性,如果我们只需要时间属性,不需要其他属性,直接序列化时间属性返回就行了。
0k,下课!!!
作者:天下没有收费的bug
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具