【发布时间】:2018-01-26 21:22:06
【问题描述】:
我有一个以下 JSON 响应,我正在从休息服务返回。现在我需要将下面的 JSON 响应反序列化为 POJO。我正在和杰克逊一起工作。
{
"pagination": {
"number": 1,
"entriesPerPage": 200,
"total": 3
},
"postings": [{
"categories": [{
"taskid": "79720",
"name": "Sunglasses",
"parentCategory": {
"taskid": "394",
"name": "Sunglasses & Fashion Eyewear",
"parentCategory": {
"taskid": "2340",
"name": "Men's Accessories",
"parentCategory": {
"taskid": "10987",
"name": "Clothing, Shoes & Accessories"
}
}
}
}]
},
{
"categories": [{
"taskid": "12980",
"name": "Toys",
"parentCategory": {
"taskid": "123",
"name": "Fashion",
"parentCategory": {
"taskid": "78765",
"name": "Men's Accessories"
}
}
}]
}],
"total": 2
}
在上面的 json 中,postings 是一个 JSON 数组,可以有多个 posting json 对象。现在categories 也是 JSON 数组。现在棘手的部分是我可以在每个类别对象中拥有多个级别的parentCategory,但我不知道我将拥有多少级别的parentCategory。给出上面的JSON,我需要提取每个类别的taskid和最后一个parentCategory的taskId。所以应该是这样的:
79720=10987
12980=78765
其中79720 是类别的taskId,10987 是最后一个parentCategory 的taskId。其他的也一样。
下面是我的代码,我通过 http 调用将 JSON 反序列化到我的 POJO 中:
ResponseEntity<Stuff> responseEntity = HttpClient.getInstance().getClient()
.exchange(URI.create(endpoint), HttpMethod.POST, requestEntity, Stuff.class);
Stuff response = responseEntity.getBody();
List<Posting> postings = response.getPostings();
for(Posting postings : postings) {
//....
}
我的困惑是 - 如何为上述 JSON 制作 POJO?我尝试使用jsonschema2pojo,但它没有为parentCategory 制作正确的课程。因为我可以拥有我事先不知道的嵌套级别的 parentCategory。
使用 Jackson 可以做到这一点吗?
这是为Category 和ParentCategory 生成的POJO 类。我不确定是否需要在此处进行任何更改,以便解析递归 parentCategory 对象。
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"taskid", "name", "parentCategory"})
public class Category {
@JsonProperty("taskid")
private String taskid;
@JsonProperty("name")
private String name;
@JsonProperty("parentCategory")
private ParentCategory parentCategory;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
...
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"taskid", "name", "parentCategory"})
public class ParentCategory {
@JsonProperty("taskid")
private String taskid;
@JsonProperty("name")
private String name;
@JsonProperty("parentCategory")
private ParentCategory parentCategory;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
...
}
【问题讨论】:
-
问题不在于对象嵌套很深,问题在于
parentCategory是递归的。搜索并阅读Jackson recursive。 -
@PeterMmm 我看过那篇文章,但我对如何在我的情况下使用
JsonManagedReference或JsonBackReference感到困惑。我已经用Category和ParentCategory对象的 POjO 更新了我的问题。
标签: java json jackson jsonpath jackson2