Deserialize object that might be wrapped

32 Views Asked by At

I need to process JSON from different sources who use different models. One is sending me

{
  "addressData": {
    "street": "Foostreet 1",
    "zip": "12345",
    "city": "Metropolis"
  }
}

and the other

{
  "addressData": {
    "address": {
      "street": "Foostreet 1",
      "zip": "12345",
      "city": "Metropolis"
    }
  }
}

i.e. the inner contents are identical, there might just be one additional layer of wrapping. So far my Java model for deserializing looks like this

class AddressData {
  private String street;
  private String zip;
  private String city;

  private Address address;
}

class Address {
  private String street;
  private String zip;
  private String city;
}

and I use an additional step in post-processing to normalize this.

Is there an annotation to tell Jackson that the object might be wrapped by an additional property, so that I can skip this boilerplate?

1

There are 1 best solutions below

0
Yasammez On

I settled for a custom delegating JsonCreator and manual mapping of the fields. Not perfect, but it will do for now. If anyone has a better solution, please let me know!

class Address {
    private String street;
    private String zip;
    private String city;

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public Address(JsonNode node) {
        var address = Optional.ofNullable(node.get("address")).orElse(node);
        street = Optional.ofNullable(address.get("street")).map(JsonNode::asText).orElse(null);
        zip = Optional.ofNullable(address.get("zip")).map(JsonNode::asText).orElse(null);
        city = Optional.ofNullable(address.get("city")).map(JsonNode::asText).orElse(null);
}