-2

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.

maximusKon
  • 136
  • 9

2 Answers2

1

You can use only the JSON library for implementing such code.

public class AddressPojo {

private String city;
private long pincode;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public long getPincode() {
    return pincode;
}

public void setPincode(long pincode) {
    this.pincode = pincode;
}

}

and now the Main Layer

public class MainLayer {

public static void main(String[] args) {
    JSONObject json = new JSONObject();
    AddressPojo addressPojo = new AddressPojo();
    addressPojo.setCity("NYC");
    addressPojo.setPincode(123343);
    json.put("name", "John");
    json.put("address", addressPojo);
    System.out.println(json.get("name")); // To Retrieve name
    JSONObject jsonObj = new JSONObject(json.get("address")); // To retrieve obj                                                                    // address                                                                  // obj
    System.out.println(jsonObj.get("city"));
}

}

That's it. Hope it helps:)

Ankit
  • 307
  • 1
  • 8
0

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.

maximusKon
  • 136
  • 9