Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

java - Jackson JSON Deserialization with Root Element

I am having a question with Jackson that I think should be simple to solve, but it is killing me.

Let's say I have a java POJO class that looks like this (assume Getters and Setters for me):

class User {
    private String name;
    private Integer age;
}

And I want to deserialize JSON that looks like this into a User object:

{
  "user":
    {
      "name":"Sam Smith",
      "age":1
  }
}

Jackson is giving me issues because the User is not the first-level object in the JSON. I could obviously make a UserWrapper class that has a single User object and then deserialize using that but I know there must be a more elegant solution.

How should I do this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...