如何在Java Spring MVC+MySQL的REST API中获取正确JSON日期格式
解决Spring MVC REST API中日期字段返回时间戳的问题
你遇到的是Jackson序列化java.util.Date时默认返回时间戳的常见问题,下面给你几种实用的解决办法:
方法一:在实体类字段上添加Jackson注解
直接在需要格式化的日期字段上使用@JsonFormat注解,指定格式和时区,Jackson序列化时就会按照你要的格式输出:
修改你的PatientMesure实体类:
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonAutoDetect; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "patient_mesure") @JsonAutoDetect public class PatientMesure { // 其他字段保留不变... @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @Column(name = "date") private Date date; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @Column(name = "inserted", nullable = false) private Date inserted; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @Column(name = "updated", nullable = false) private Date updated; // getters and setters }
pattern:指定目标日期格式,这里就是你需要的yyyy-MM-dd HH:mm:sstimezone:设置时区(比如中国时区用GMT+8),避免出现日期偏移的问题
方法二:全局配置Jackson(推荐)
如果项目中有大量日期字段需要统一格式化,逐个加注解太繁琐,可以全局配置Jackson的日期序列化规则:
若使用Spring Boot
直接在application.properties中添加配置:
# 指定日期格式化规则 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss # 设置时区 spring.jackson.time-zone=GMT+8
或者在application.yml中配置:
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
若使用传统Spring MVC
自定义WebMvcConfigurer配置消息转换器:
import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.fasterxml.jackson.databind.ObjectMapper; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); objectMapper.setDateFormat(sdf); converter.setObjectMapper(objectMapper); converters.add(converter); } }
额外建议:使用Java 8日期API(更优雅)
如果项目支持Java 8+,建议把java.util.Date替换为Java 8的LocalDateTime(不带时区)或ZonedDateTime(带时区),这些API设计更合理,能避免很多日期相关的坑。使用时同样可以配合@JsonFormat或全局配置:
import java.time.LocalDateTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "date") private LocalDateTime date;
完成以上配置后,重启服务再调用/getAllMesures接口,返回的日期字段就会变成你想要的2018-05-31 21:14:12格式啦!
内容的提问来源于stack exchange,提问作者user9816511
相关产品推荐
相关产品推荐

