本文介绍了使用Spring Boot自动转换RequestBody时将ZonedDateTime的时区更改为UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保留在对Spring Boot控制器执行POST / PUT时在前端设置的ZonedDateTime的ZoneId。

I'm trying to keep ZoneId of ZonedDateTime which is set on front-end while performing POST/PUT to Spring Boot controller.

我要传输的值是:
2019-05-01T00:00:00 + 01:00 [欧洲/萨格勒布]

POST / PUT之后,将ZoneId转换为UTC并调整小时数。从技术上讲,此更新的值表示时间轴上的同一点,但是原始的ZoneId丢失了,我希望将其存储起来以便以后再显示给最终用户。

After POST/PUT the ZoneId is converted to UTC and hours are adjusted. Technically this updated value represents the same point on time line, but the original ZoneId is lost and I would like to have it stored to be able to show it back later to end user.

// DTO
public class PriceInfoDTO {
    @JsonFormat( pattern = "yyyy-MM-dd'T'HH:mm:ssXXX['['VV']']",
        with = JsonFormat.Feature.WRITE_DATES_WITH_ZONE_ID )
    @DateTimeFormat( pattern = "yyyy-MM-dd'T'HH:mm:ssXXX['['VV']']", iso = ISO.DATE_TIME )
    private ZonedDateTime validFrom;
}


// Controller
@PutMapping(
    path = PATH + "/{id}",
    consumes = MediaType.APPLICATION_JSON_VALUE,
    produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<PriceInfo> update(
    @PathVariable("id") final Integer id,
    @RequestBody final PriceInfoDTO dto
) {
    System.out.println(dto);
    ...
}

在浏览器中的网络标签上,从浏览器到Spring Controller的请求具有此值(有效负载):

Looking at Network tab in my browser, the request from browser to Spring Controller has this value (payload):

2019-05-01T00:00:00+01:00[Europe/Zagreb]

与格式模式相同。

当我将DTO转储到控制台时,会得到以下结果:

When I dump DTO to console, I get this result:

2019-04-30T22:00Z[UTC]

有什么方法可以保留在请求中收到的ZoneId吗?我应该编写自己的序列化器和反序列化器来实现这一目标吗?

Is there any way to preserve ZoneId as it was received in a request? Should I write my own Serializer and Deserializer to achieve this?

谢谢!

推荐答案

将以下行添加到 application.properties 文件:

spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false






引用:


References:


  • Baeldung: Jackson日期:

  • Javadoc: jackson-databind 2.6.0 API:

  • Spring Boot:操作方法 G uides:

  • Baeldung: Jackson Date: Deserialize Joda ZonedDateTime with Time Zone Preserved
  • Javadoc: jackson-databind 2.6.0 API: ADJUST_DATES_TO_CONTEXT_TIME_ZONE
  • Spring Boot: "How-to" Guides: Customize the Jackson ObjectMapper

这篇关于使用Spring Boot自动转换RequestBody时将ZonedDateTime的时区更改为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:21