欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

SpringBoot中处理JSON日期格式方式,

来源: javaer 分享于  点击 34173 次 点评:256

SpringBoot中处理JSON日期格式方式,


目录
  • Spring Boot中处理JSON日期格式
    • 一、@JsonFormat
    • 二、 配置默认格式
    • 三、自定义Jackson的ObjectMapper
  • 总结

    Spring Boot中处理JSON日期格式

    Spring Boot web,往往需要对返回的日期格式进行相应的处理,以下列出目前常用的三种处理日期格式的方式。

    一、@JsonFormat

    需要在每个日期属性上,添加@JsonFormat注解,可以是LocalDate 或Date。

    public class Contact {
    
        @JsonFormat(pattern="yyyy-MM-dd")
        private LocalDate birthday;
         
        
      @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Europe/Zagreb")
    
    
    private Date lastUpdate;
    
    }

    这样在就可以获得以下输出:

    {
        "birthday": "2019-02-03",
        "lastUpdate": "2019-02-03 10:08:02"
    }

    二、 配置默认格式

    上面方法是对每个日期进行硬编码,但是如果系统大部分日期需要采用某种格式,则统一设置最方便,可以在配置中添加以下属性,则所有的日期都会转换成相应的格式。

    对于个别需要特殊处理的,再使用注解单独配置。

    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    spring.jackson.time-zone=Europe/Zagreb

    三、自定义Jackson的ObjectMapper

    除了使用配置,还可以通过编码的方式,不过配置肯定最方便,编码的方式是能够处理更多的个性化内容,如果只是配置日期,有点大材小用了。

    @Configuration
    public class ContactAppConfig {
    
        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)));
            };
        }
    
    }

    虽然这种方法看起来有点麻烦,但好处是它适用于 Java 8 和传统的日期类型。

    总结

    以上是spring boot中处理日期的常用的三种方式,按照需要选择即可。

    这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。

    您可能感兴趣的文章:
    • SpringBoot定制JSON响应数据的实现
    • SpringBoot中Json工具类的实现
    • Springboot通过ObjectMapper配置json序列化详解
    • SpringBoot压缩json并写入Redis的示例代码
    • SpringBoot返回long,前端接收进度丢失,@JsonSerialize不生效问题
    • SpringBoot设置Json返回字段为非空问题
    • springboot统一返回json数据格式并配置系统异常拦截方式
    相关栏目:

    用户点评