Search code examples
javajsonfasterxml

Map nested json field


I have json like this:

{
  "name": "John",
  "address": {
    "city": "New York"
  }
}

How can I deserialize it to the follow dto using Jackson?

final class PersonDto {
  private final String name; // name
  private final String city; // address.city

  public PersonDto(String name, String city) {
  this.name = name;
  this.city = city;
 }
}

Essentially I am interesting, is it possible to map nested field 'city' in json using just constructor and annotations, or should I write custom deserializer? Thank you.


Solution

  • The best way I have found to solve my problem in appropriate way is using @JsonCreator annotation with @JsonProperty. So then the code will look like:

    final class PersonDto {
      private final String name; // name
      private final String city; // address.city
    
      public PersonDto(String name, String city) {
        this.name = name;
        this.city = city;
      }
    
      @JsonCreator
      public PersonDto(@JsonProperty("name") String name, @JsonProperty("address") Map<String, Object> address) {
        this(name, address.get("city"))
      }
    }
    

    Of course it's the best way if you deserialize merely simple POJO. If you deserialization logic is more complex, it's better to implement your own custom deserializer.