Java存入数据库的DATE字段返回JSON为时间戳,如何转为日期格式?
解决Java Date类型字段JSON序列化显示时间戳的问题
方案一:字段级别添加注解(Jackson框架)
在实体类的rkd字段上添加@JsonFormat注解,指定日期格式与时区,避免时区偏移导致日期错误:
import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class YourEntity { // 其他字段省略 @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private Date rkd; // getter、setter方法 }
方案二:全局配置日期序列化规则(Spring Boot项目)
如果不想逐个字段配置,可在Spring Boot配置文件中全局设置Date类型的序列化格式:
application.properties配置:
spring.jackson.date-format=yyyy-MM-dd spring.jackson.time-zone=GMT+8
application.yml配置:
spring: jackson: date-format: yyyy-MM-dd time-zone: GMT+8
方案三:FastJSON框架下的配置
如果项目使用FastJSON作为JSON序列化工具,有两种配置方式:
字段级别注解
import com.alibaba.fastjson.annotation.JSONField; import java.util.Date; public class YourEntity { // 其他字段省略 @JSONField(format = "yyyy-MM-dd") private Date rkd; // getter、setter方法 }
全局配置
通过配置类统一设置FastJSON的日期序列化规则:
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration public class FastJsonConfigurer implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd"); config.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat); converter.setFastJsonConfig(config); converters.add(0, converter); } }
问题原因说明
默认情况下,Jackson、FastJSON等JSON序列化框架会将java.util.Date类型序列化为时间戳,这是框架的默认行为。通过上述配置或注解,可强制框架按照指定的日期格式输出字符串。
内容的提问来源于stack exchange,提问作者Franky
相关产品推荐
相关产品推荐

