杰克逊,反序列化嵌套对象

Jackson, deserializing nested object

我有以下请求结构,应该由 spring 反序列化:

{
  "firstname": "Iev",
  "lastname": "Ivano",
  "createdProfile": {
    "from": "2019-07-03T15:41:52.854+03:00",
    "to": "2019-07-05T15:41:52.854+03:00"
  }
}

我的 DTO 看起来像

class UserDto {

    private String firstname;

    private String lastname;

    @JsonProperty("createdProfile.from")
    private ZonedDateTime createdProfileFrom;

    @JsonProperty("createdProfile.to")
    private ZonedDateTime createdProfileTo;
    //gets 
    //sets
}

所以我希望 spring 填充

 ZonedDateTime createdProfileFrom and ZonedDateTime createdProfileTo

来自

 "createdProfile": {
    "from": "2019-07-03T15:41:52.854+03:00",
    "to": "2019-07-05T15:41:52.854+03:00"
  }

考虑到我用

注释了相应的字段
  @JsonProperty("createdProfile.from") and @JsonProperty("createdProfile.to") 

但出于某种原因 spring 不想填充这些字段。

将不胜感激,

谢谢

您的 UserDto 对象应如下所示:

public class UserDto {

  private String firstname;
  private String lastname;
  private ZonedDateTime createdProfileFrom;
  private ZonedDateTime createdProfileTo;

  @JsonProperty("createdProfile")
  private void unpackNested(Map<String,Object> elements) {
    this.createdProfileFrom = ZonedDateTime.parse((String)elements.get("from"), DateTimeFormatter.ISO_DATE_TIME);
    this.createdProfileTo = ZonedDateTime.parse((String)elements.get("to"), DateTimeFormatter.ISO_DATE_TIME);
  }

   //getters + setters
}

在反序列化期间,您可以使用注释访问 createdProfile 元素,并在方法本身中读取嵌套元素。