Jackson JSON Deserialization with Root Element

Solution 1:

edit: this solution only works for jackson < 2.0

For your case there is a simple solution:

  • You need to annotate your model class with @JsonRootName(value = "user");
  • You need to configure your mapper with om.configure(Feature.UNWRAP_ROOT_VALUE, true); (as for 1.9) and om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); (for version 2).

That's it!


@JsonRootName(value = "user")
public static class User {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(final Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + "]";
    }

}

ObjectMapper om = new ObjectMapper();
om.configure(Feature.UNWRAP_ROOT_VALUE, true);
System.out.println(om.readValue("{  \"user\":    {      \"name\":\"Sam Smith\",      \"age\":1  }}", User.class));

this will print:

User [name=Sam Smith, age=1]