Say I have the following class:
public class Parent {
public int age;
@JsonUnwrapped
public Name name;
}
Producing JSON:
You can use @JsonCreator
with @JsonProperty
for each field:
@JsonCreator
public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName) {
this.age = age;
this.name = new Name(firstName, lastName);
}
Jackson does type checking and unknown field checking for you in this case.
@JsonUnwrapped
works for both serialization and deserialization, you shouldn't need to take any additional steps.
It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped
here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138
For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map
, there is a solution with @JsonAnySetter
:
public class CountryList
{
Map<String, Country> countries = new HashMap<>();
@JsonAnySetter
public void setCountry(String key, Country value)
{
countries.put(key, value);
}
}