Jackson JSON 反序列化与根元素 [英] Jackson JSON Deserialization with Root Element

查看:44
本文介绍了Jackson JSON 反序列化与根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对杰克逊有一个我认为应该很容易解决的问题,但它让我很沮丧.

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

假设我有一个看起来像这样的 Java POJO 类(假设我有 Getter 和 Setter):

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;
}

我想将像这样的 JSON 反序列化为 User 对象:

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

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

Jackson 给我带来了问题,因为 User 不是 JSON 中的第一级对象.我显然可以创建一个包含单个 User 对象的 UserWrapper 类,然后使用它进行反序列化,但我知道必须有一个更优雅的解决方案.

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.

我该怎么做?

推荐答案

edit: 此解决方案仅适用于 jackson <2.0

对于您的情况,有一个简单的解决方案:

For your case there is a simple solution:

  • 你需要用 @JsonRootName(value = "user") 注释你的模型类;
  • 您需要使用 om.configure(Feature.UNWRAP_ROOT_VALUE, true);(对于 1.9)和 om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); 来配置映射器.(适用于版本 2).
  • 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).

就是这样!

@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));

这将打印:

User [name=Sam Smith, age=1]

这篇关于Jackson JSON 反序列化与根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆