一、背景说明

在使用SpringBoot+SpringMVC时,默认采用Jackson包来进行JSON转换。

在返回Date类型的数据时,Jackson会以时间戳的形式返回,而实际场景往往需要以yyyy-MM-dd HH:mm:ss这类日期或时间格式返回。

二、解决方案

有几种方式可以对Date格式进行设置:

1. 在application.properties中做全局配置

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false

2. 在单个实体类的属性上面使用@JsonFormat注解

如果你的Date类型要返回一个非yyyy-MM-dd HH:mm:ss格式的信息,则需要使用@JsonFormat注解:

/*
* 消息推送时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date messagePushTime;

3. 采用@JsonComponent注解,来实现JsonSerializer和JsonDeserializer

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;

@JsonComponent
public class Example {

    public static class Serializer extends JsonSerializer<SomeObject> {
        // ...
    }

    public static class Deserializer extends JsonDeserializer<SomeObject> {
        // ...
    }

}

三、参考链接

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-docs/src/main/asciidoc/appendix-application-properties.adoc

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-json-components

 

2 对 “SpringBoot Jackson Date类型格式设置”的想法;

发表评论

邮箱地址不会被公开。 必填项已用*标注