如何使用Lombok映射嵌套的JSON

时间:2015-08-31 15:52:14

标签: lombok spring-rest

我有这个JSON API响应:

{
  "_links": {
    "self": {
      "href": "http://xxx/person{?page,size,sort}",
      "templated": true
    }
},
"_embedded": {
"person": [
  {
    "datetimeCreated": "2015-08-27T11:21:34.000+0000",
    "datetimeLastUpdated": "2015-08-27T11:21:34.000+0000",
    "middleName": "Patricia"
  }
]
},
"page": {
  "size": 20,
  "totalElements": 2,
  "totalPages": 1,
  "number": 0
  }
}

我有这个类来映射响应:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private Links _links;
    private Person _embedded;
    private Page page;
}

我可以使用Page class:

映射'page'
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Page {
    private Integer size;
    private Integer totalElements;
    private Integer totalPages;
    private Integer number;
}

但是,如何映射'_embedded'和'_links'?如果我使用相同的方法映射_links和_embedded,则此字段的值为null。

1 个答案:

答案 0 :(得分:1)

json与您的数据模型不匹配。例如,您已将_embedded字段声明为Person的类型。但Person依次为_linkspage等字段

对我来说,正确的数据模型似乎是:

  @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public class Person1 {
    private Links _links;
    private Embedded _embedded;
    private Page page;

  @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Page {
    private Integer size;
    private Integer totalElements;
    private Integer totalPages;
    private Integer number;
  }

  @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public class Links {
    private Self self;
  }

  @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Embedded {
    private List<Person> person;
  }

  @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Self {
    private String href;
    private boolean templated;
  }

  @Data
  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Person {
    private DateTime datetimeCreated;
    private DateTime datetimeLastUpdated;
    private String middleName;
  }
}