Java Jackson Mapper-嵌套属性

时间:2018-08-16 20:32:09

标签: java json jackson

我有2个简单的实体

public class User {
    public int id;
    public String name;
}
public class Item {
    public int id;
    public String name;
    public User owner;
}

Jackson可以成功反序列化此json。

{
    "id": 1,
    "name": "theItem",
    "owner": {
        "id": 2,
        "name": "theUser"
    }
}

new ObjectMapper().readValue(JSON, Item.class);

问题

我想知道是否可以在不创建另一个实体(Item2.class)的情况下反序列化下一个json。

我想使用Item.class反序列化它

{
      "id": 1,
      "name": "theItem",
      "owner_id": 2,
      "owner_name": "theUser"
  }



  public class Item2 {
        public int id;
        public String name;
        public int owner_id;
        public String owner_name;
    }

这有可能吗?

1 个答案:

答案 0 :(得分:1)

是的,您可以这样做,但是只需创建Map<String,Object> Jackson即可将值转换为Integers或String,下面是有效的代码

public class Item {

public int id;
public String name;
public Map<String, Object> owner ;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Map<String, Object> getOwner() {
    return owner;
}
public void setOwner(Map<String, Object> owner) {
    this.owner = owner;
  }

}