Say I have the following class:
public class Parent { public int age; @JsonUnwrapped public Name name; }
Producing JSON:
{ "age" : 18, "first" : "Joey", "last" : "Sixpack" }
How do I deserialize this back into the Parent class? I could use @JsonCreator
@JsonCreator public Parent(Map<String,String> jsonMap) { age = jsonMap.get("age"); name = new Name(jsonMap.get("first"), jsonMap.get("last")); }
But this also effectively adds @JsonIgnoreProperties(ignoreUnknown=true)
to the Parent class, as all properties map to here. So if you wanted unknown JSON fields to throw an exception, you'd have to do that yourself. In addition, if the map values could be something other than Strings, you'd have to do some manual type checking and conversion. Is there a way for Jackson to handle this case automatically?
Edit: I might be crazy, but this actually appears to work despite never being explicitly mentioned in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html
I was pretty sure it didn't work for me previously. Still, the proposed @JsonCreator approach might be preferred when custom logic is required to deserialize unwrapped polymorphic types.
@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization.
The @JsonIgnore annotation marks a field of a POJO to be ignored by Jackson during serialization and deserialization. Jackson ignores the field both JSON serialization and deserialization. An example of Java class that uses the @JsonIgnore annotation is this.
@JsonProperty can change the visibility of logical property using its access element during serialization and deserialization of JSON. @JsonAlias defines one or more alternative names for a property to be accepted during deserialization.
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With