Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Jackson deserialization equivalent of @JsonUnwrapped?

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.

like image 998
Shaun Avatar asked May 15 '13 16:05

Shaun


People also ask

What is @JsonUnwrapped?

@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization.

What is JsonIgnore Jackson?

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.

What is difference between JsonProperty and JsonAlias?

@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.

What is @JsonProperty?

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.


1 Answers

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.

like image 154
hoaz Avatar answered Oct 01 '22 12:10

hoaz