![](/img/trans.png)
[英]How to assert two JSON objects which have the same keys but different in values inside of a JSON array
[英]How to treat JSON Array with response are two objects childrens, but different content
大家晚安,嗨,我的基於 reddit API 的應用程序有一個問題,我在其中調用帖子詳細信息路由,響應是一組數據對象,但主要孩子指的是帖子。 第二個是您的評論。
完整的回應:
[
{
"kind": "Listing",
"data": {
"modhash": "",
"dist": 1,
"children": [],
"after": null,
"before": null
}
},
{
"kind": "Listing",
"data": {
"modhash": "",
"dist": null,
"children": [],
"after": null,
"before": null
}
}
]
第一個孩子是基於帖子的數組數據,第二個孩子是基於帖子評論的數組數據。 兩者都有不同的領域,也就是說,在第一個孩子中,它沒有第二個孩子的所有領域,例如
處理這種結果的最佳方法是什么,無論是在 kotlin 還是 java 中?
你不能只是反序列化它,下面似乎工作正常(我沒有費心添加所有字段)?
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try (FileInputStream fs = new FileInputStream("reddit.json")) {
Reddit[] reddit = mapper.readValue(fs, Reddit[].class);
System.out.println(reddit[0].kind);
System.out.println(reddit[0].data.children[0].data.thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class Reddit {
public final String kind;
public final Data data;
@JsonCreator
public Reddit(
@JsonProperty("kind") String kind,
@JsonProperty("data") Data data
) {
this.kind = kind;
this.data = data;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Data {
public final String modhash;
public final Integer dist;
public final ChildData[] children;
public final String after;
public final String before;
@JsonCreator
public Data(
@JsonProperty("modhash") String modhash,
@JsonProperty("dist") Integer dist,
@JsonProperty("children") ChildData[] children,
@JsonProperty("after") String after,
@JsonProperty("before") String before
) {
this.modhash = modhash;
this.dist = dist;
this.children = children;
this.after = after;
this.before = before;
}
}
public static class ChildData {
public final String kind;
public final ChildDataData data;
@JsonCreator
public ChildData(
@JsonProperty("kind") String kind,
@JsonProperty("data") ChildDataData data
) {
this.kind = kind;
this.data = data;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ChildDataData {
public final Integer total_awards_received;
public final String body;
public final String thumbnail;
@JsonCreator
public ChildDataData(
@JsonProperty("total_awards_received") Integer total_awards_received,
@JsonProperty("body") String body,
@JsonProperty("thumbnail") String thumbnail
) {
this.total_awards_received = total_awards_received;
this.body = body;
this.thumbnail = thumbnail;
}
}
類似的事情,您可能想將名稱更改為對您有意義的名稱,並且您需要將所有字段添加到 ChildDataData 但我認為您明白了嗎?
Gradle 依賴項
dependencies {
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.2'
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.12.2'
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.