是否可以使用Jackson将JSON字段分组为一个属性?

时间:2018-11-23 11:06:32

标签: java json jackson

我想知道是否有任何方法可以将几个JSON字段反序列化为一个Java属性。例如。给定此JSON:

{
  "id" : "1",
  "name" : "Bartolo",
  "address" : "whatever",
  "phone" : "787312212"
}

将其反序列化为此类:

public class Person {

    public String id;
    public String name:

    @JsonProperty(names = {"address", "phone"}) //something like this
    public String moreInfo;

}

所以moreInfo等于"whatever, 787312212"或类似的东西。

在不使用自定义解串器的情况下这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用@JsonCreator注释,如下所示:

String json = {"id" : "1",  "name" : "Bartolo", "address" : "whatever", "phone" : "787312212" }

ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json , Person.class);

并在您的Person类的构造函数中添加此

@JsonCreator
public Person(@JsonProperty("address") String address, @JsonProperty("phone") String phone) {
    this.moreInfo = address + "," phone;
}