Spring Boot 格式化接口返回JSON中的日期/日期时间(LocalDate/LocalDateTime)

导读:本篇文章讲解 Spring Boot 格式化接口返回JSON中的日期/日期时间(LocalDate/LocalDateTime),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Spring Boot默认使用JackJson作为json转换器,用于生成JSON格式数据,有时候它格式化的日期/日期时间(LocalDate/LocalDateTime)字段并不符合产品的需求,因此需要对它返回的json中的日期和日期时间类型的字段做自定义格式处理。

 

1、在字段上使用@JsonFormat

@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate birthday;  // 生日
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime; // 系统写入时间

这种方式很灵活,但是由于我使用了MyBatis Generator自动生成数据层代码,不能修改自动生成的Model类,因为随时有可能会删除掉这份MyBatis Generator生成的数据层代码,然后重新再生成一份。

 

2、在application.properties 统一配置

(1)处理非Java 8的日期类型

非Java 8的日期和日期时间类型,可以在application.properties做如下配置,全局范围控制日期时间的格式化

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

(2)处理Java 8的日期类型

上述第一种配置对Java 8类型的日期和日期时间(LocalDate、LocalDateTime)不起效,只能处理遗留的日期格式(如java.util.Date),如果要处理Java 8的日期类型,需要在Spring Boot的SpringMvc配置类中定义Jackson的日期转换格式,如下所示:

/**
 * @author 李海林 手机:13802780104|微信:lihailin9073|Email:767679879@qq.com
 * @copyright 个人开发者李海林版权所有,产品详情及技术服务请登录官网查询[http://www.x-core.org.cn]
 * @create 2019-08-20 18:26
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private static final String dateFormat = "yyyy-MM-dd";
    private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.simpleDateFormat(dateTimeFormat);
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
        };
    }
    
}

这样定义之后,所有被Jackson转换为json格式的日期和日期时间都会统一按照上述代码定义的格式进行处理。

 

3、自定义JSON转换器来处理日期格式

通过自定义JSON转换器,去掉Spring Boot默认的Jackson-databind,引入FastJson作为新的JSON转换器,然后在自定义FastJson转换器的时候对日期时间进行格式化处理

(1)在pom中引入FastJson并屏蔽more的Jackson-databind


        <!-- 在引入web依赖时,屏蔽掉jackson转换器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 引入fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.48</version>
        </dependency>

(2)配置 fastjson 的 HttpMessageConverter

package cn.org.xcore.edusys.config;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;

/**
 * FastJson配置类
 *
 * @author 李海林 手机:13802780104|微信:lihailin9073|Email:767679879@qq.com
 * @copyright 个人开发者李海林版权所有,产品详情及技术服务请登录官网查询[http://www.x-core.org.cn]
 * @create 2019-08-29 21:35
 */
@Configuration
public class InitFastJsonConfig {

    @Bean
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter () {
        FastJsonHttpMessageConverter converter= new FastJsonHttpMessageConverter();

        // 创建FastJson转换器的配置
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式
        config.setCharset(Charset.forName("UTF-8")); // 设置编码格式


        converter.setFastJsonConfig(config);

        return converter;
    }

}

通过这两步的配置,就启用了FastJson作为json转换器,并且设置了日期的格式为 yyyy-MM-dd HH:mm:ss

 

 

订单

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/10479.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!