I have a JSON string that contains a nested and wrapped JSON string. I'd like to deserialize this using Jackson but I'm unsure how. Here's a sample bean:
@JsonIgnoreProperties(ignoreUnknown = true)
public class SomePerson {
public final String ssn;
public final String birthday;
public final Address address;
@JsonCreator
public SomePerson(
@JsonProperty("ssn") String ssn,
@JsonProperty("birthday") String birthday,
@JsonProperty("data") Address address,
@JsonProperty("related") List<String> related) {
this.ssn = ssn;
this.birthday = birthday;
this.address = address;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Address {
public final String city;
public final String country;
@JsonCreator
public Address(
@JsonProperty("city") String city,
@JsonProperty("country") String country) {
this.city = city;
this.country = country;
}
}
}
The JSON string resembles this:
{
ssn: "001",
birthday: "01.01.2020",
address: "{ city: \"London\", country: \"UK\" }"
}
While I've deserialized nsted objects before - I'm rather lost as to how to do this when the object is a wrapped string.
When internal object is escaped
JSON String
we need to deserialise it "twice". First time is run when rootJSON Object
is deserialised and second time we need to run manually. To do that we need to implement custom deserialiser which implementscom.fasterxml.jackson.databind.deser.ContextualDeserializer
interface. It could look like this:We need to annotate our property with this class:
Since now, you should be able to deserialise above
JSON
payload to yourPOJO
model.See also: