Jackson, deserializing nested object

Andrey Yaskulsky :

I have the following request structure which should be deserialized by spring:

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

My DTO looks like

class UserDto {

    private String firstname;

    private String lastname;

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

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

So I want spring to populate

 ZonedDateTime createdProfileFrom and ZonedDateTime createdProfileTo

from

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

taking into account that I annotated corresponding fields with

  @JsonProperty("createdProfile.from") and @JsonProperty("createdProfile.to") 

But for some reason spring does not want to populate these fields.

Will appreciate any help,

Thanks

taygetos :

Your UserDto object should look like this:

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
}

during deserialization you access to the createdProfile element with the annotation and in the method itself you read the nested elements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134782&siteId=1