What's the Jackson deserialization equivalent of @JsonUnwrapped?

Shaun picture Shaun · May 15, 2013 · Viewed 20.2k times · Source

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.

Answer

hoaz picture hoaz · May 15, 2013

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.