简体   繁体   English

Spring - 如何将请求模型中 JSON 正文字段中日期的字符串表示形式转换为 OffsetDateTime

[英]Spring - How to convert a String representation of Date in JSON body field in request model comming into controller to OffsetDateTime

I have legacy data coming in to my API as part of UserRequest model like我有遗留数据作为UserRequest模型的一部分进入我的 API,例如

@PostMapping
public MyResponse saveUser(@Valid @RequestBody UserRequest userRequest) {
   ...
}

UserRequest class uses OffsetDateTime for dateRegistered field: UserRequest 类对dateRegistered字段使用 OffsetDateTime:

public class UserRequest {
   ...
   OffsetDateTime birthDate;
   ...
}

The problem I am having is that the data is coming into the API using below format for dateRegistered field:我遇到的问题是数据使用以下dateRegistered字段格式进入 API:

{
    "last-name":"Mikel",
    "birth-date":"20200716"
}

So, the string representation "20200716" from JSON request needs to be somehow converted to OffsetDateTime like "2020-07-16T00:00:00Z" (the time portion and offset is set to 0s).因此,来自 JSON 请求的字符串表示“20200716”需要以某种方式转换为 OffsetDateTime,如“2020-07-16T00:00:00Z”(时间部分和偏移设置为 0s)。

By default, the " 20200716 ":默认情况下,“ 20200716 ”:

{
    "last-name":"Mikel",
    "birth-date":"20200716"
}

, gets converted to OffsetDateTime value of , 转换为OffsetDateTime

{
    "last-name": "Mikel",
    "birth-date": "1970-08-22T19:18:36Z"
}

, which is obviously way off. ,这显然是遥不可及的。

How do I convert a string representation of date in Json field like " 20200716 " to its OffsetDateTime representation like " 2020-07-16T00:00:00Z " or " 2020-07-16T00:00:00.000+00:00 "?如何将 Json 字段中日期的字符串表示形式(如“ 20200716 ”)转换为其OffsetDateTime表示形式,如“ 2020-07-16T00:00:00Z ”或“ 2020-07-16T00:00:00.000+00:00 ”?

I was trying to annotate my OffsetDateTime field with @JsonFormat("yyyyMMdd") but that is throwing exception like: JSON parse error: Cannot deserialize value of type java.time.OffsetDateTime from String "20200716" .我试图用@JsonFormat("yyyyMMdd")注释我的OffsetDateTime字段,但这会引发异常,例如: JSON parse error: Cannot deserialize value of type java.time.OffsetDateTime from String "20200716"

you don't need a JSON annotation.您不需要 JSON 注释。 You need to adjust the setter as follow.您需要按如下方式调整设置器。

public class MedicalCandidateRequest {
   
    private OffsetDateTime dateRegistered;
   
    public OffsetDateTime getDateRegistered() {
        return dateRegistered;
    }
  
    public void setDateRegistered(String dateString) {
        final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSxx";
        DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern(pattern);
        this.dateRegistered = OffsetDateTime.parse(dateString, dtFormatter );
    }
}

Change the parameter of the setter method to a String and do the conversion yourself.将 setter 方法的参数更改为 String 并自己进行转换。

public void setDateRegistered(String value) {
   this.dateRegistered = doConversionHere(value);
}

Thanks for suggestions but I have decided to go with my own implementation.感谢您的建议,但我决定采用自己的实施方式。

I provided a custom deserializer like:我提供了一个自定义反序列化器,例如:

public class CustomDateDeserializer extends JsonDeserializer<OffsetDateTime> {

    private static final String PATTERN = "yyyyMMdd";

    private final DateTimeFormatter formatter;

    public CustomDateDeserializer() {
        this.formatter = DateTimeFormatter.ofPattern(PATTERN);
    }

    @Override
    public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException, JacksonException {

        LocalDate localDate = LocalDate.parse(parser.getText), formatter);
        OffsetDateTime offsetDateTime = OffsetDateTime.of(localDate, LocalTime.MIDNIGHT, ZoneOffset.UTC);

        return offsetDateTime;
    }
}

, which I then use to annotate my model field like: ,然后我用它来注释我的模型字段,例如:

@JsonDeserialize(using = CustomDateDeserializer.class)
private OffsetDateTime birthDate;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以字符串形式获取请求正文的 JSON 表示 - Get JSON representation of request body as a string 无法将JSON作为请求正文发送到Spring Controller - Cannot send JSON as request body to Spring Controller 如何将日期数组的字符串表示形式转换为数组JS? - How convert a string representation of date array to array JS? 如何在请求正文中发布 JSON 字符串而不是 Object? - How to post JSON String NOT Object in request body? 在 Spring Boot 2 中将包含带引号的字符串的请求正文解析为 JSON - Parsing a request body containing a quoted string as JSON in Spring Boot 2 将http body请求中的JSON数据转换为PowerShell中的字符串 - Convert JSON data from http body request to string in PowerShell 默认时间戳格式设置为其他格式时,如何在Spring Boot控制器请求正文中传递日期yyyy-mm-dd - how to pass date yyyy-mm-dd in spring boot controller request body when default timestamp format set to something else 如何创建json的字符串表示形式 - how to create a string representation of json 我如何在Spring Controller中接收JSON作为正文? - how can i receive json as body in spring controller? Spring boot 的 Postman Post 请求保存了整个 JSON 正文,而不仅仅是字段值。 我该如何解决? - Postman Post request for Spring boot saves the entire JSON body instead of just the field value. How do I fix this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM