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

目录

1、异常信息

2、异常原因

3、解决方案


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

1、异常信息

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)

2、异常原因

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

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

2.2、jackjson解析框架在解析实体类里面是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’,所以就会出现上面的异常。

3、解决方案

方案一:将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

或者写成以下格式(主要取决于配置文件是什么格式的):

#日期格式化
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注解格式化日期(这个方法有时候可以,有时候不行)

    /**
     * 创建时间
     */
    @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")
发布了146 篇原创文章 · 获赞 221 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_44299027/article/details/104516280