SpringBoot中jackson日期格式化问题(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS not turning off timestamps)

本文目录

一、异常信息

二、异常原因

三、解决方案


最近在做一个Springboot项目,中间遇到一个问题就是日期的格式化,每次实体类中的字段为Date类型时,从前端传到后台的时间格式老出错,属性字段上也加上@DateJsonFormat@JsonFormat注解了,但还是不行,后台报错,,在MVC环境中显示正常,到了springboot中就由2019-03-06 06:14:32 变成了 2020-02-19T06:14:32.005+0000,经查是由于Jackson未在springboot环境中配置对应的日期格式导致。

一、异常信息

org.springframework.web.client.RestClientException: Error while extracting response for type
[class com.imooc.entity.Product] and content type [application/json;charset=UTF-8];
 nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
 JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2020-02-19 21:33:16":
 not a valid representation (error: Failed to parse Date value '2020-02-19 21:33:16':
 Cannot parse date "2020-02-19 21:33:16": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',
 parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: 
Cannot deserialize value of type `java.util.Date` from String "2020-02-19 21:33:16": not a valid representation (error: Failed to parse Date value '2020-02-19 21:33:16': 
Cannot parse date "2020-02-19 21:33:16": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
 at [Source: (PushbackInputStream); line: 1, column: 141] (through reference chain: com.imooc.entity.Product["createAt"])
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:115)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:689)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:644)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:399)
    at com.imooc.util.RestUtil.postJSON(RestUtil.java:31)
    at com.imooc.controller.ProductControllerTest.lambda$0(ProductControllerTest.java:59)
    at java.util.ArrayList.forEach(Unknown Source)

二、异常原因

主要问题就是实体类的Date转化Json过程出现错误。

2.1、Springboot默认使用的json解析框架是jackson框架

2.2、jackson解析框架在解析实体类里面是Date数据类型的数据时的默认格式是:UTC类型,即yyyy-MM-dd’T’HH:mm:ss.SSS 并且默认为+8时区,即时间基础上加8小时

请求数据格式为: 'yyyy-MM-dd HH:mm:ss',但是在接收到数据的时候,需要通过jackson把数据转化成Dto对象。jackson转化的时候,默认的时间格式是 'yyyy-MM-dd'T'HH:mm:ss.SSS’,所以就会出现上面的异常。

三、解决方案

方案一:将spring的jackson日期格式写在配置文件中即可

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

spring:
  application:
    name: operation-service
    system: wisdomhome
  main:
    allow-bean-definition-overriding: true    
  profiles:
    active: local
  servlet:
    multipart:
      max-file-size: 1024MB
      max-request-size: 1024MB
          
  cloud:
    zookeeper:
      discovery:
        enabled: true
        register: true
        root: /immoc-service
      connectString: dev.soft.com:53200
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-dates-as-timestamps: false

或者写成以下格式(主要取决于配置文件是yml, 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

方案二:在实体Date类型的字段上使用@JsonFormat注解格式化日期(这个方法有时候可以,有时候不行)

此方案要注意 timezone 值的写法,不要在 “+”号两边留空格,如果加号两边有空格会导致解析失败的哦~~~

    /**
     * 创建时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT + 8")
    private Date createTime;

方案三:通过下面方式取消timestamps形式

objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

其他方案:

如果项目中使用json解析框架为fastjson框架,则可使用如下解决方法:在实体字段上使用@JsonFormat注解格式化日期

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")

完结!

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

No8g攻城狮

向每一个努力改变现状的你致敬!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值