ブレンダン・ウェイドマホーニー:
RedditのJSON APIでは、コメントはJSONArrays二つの異なるタイプの、「子供」と呼ばれる、両方を含めることができます。
「子どもたちは」「データ」「種類」文字列やオブジェクトを含むオブジェクトの配列は、通常は次のとおりです。
"children": [ { "kind": "t3", "data": {} } ...]
私はこれらの罰金を処理してきました。私の問題は、時々、子供たちは、単純な文字列配列になるということです。
"children": [ "e78i3mq", "e78hees", "e78jq6q" ]
これらを解析すると、GSONは、次のような例外がスローされます:
java.lang.IllegalStateException:によって引き起こさ期待BEGIN_OBJECTが、行1列3780パス$でSTRINGだった[1] .data.children [0] .data.replies.data.children [0] .data.replies.data.children [0] .data.replies.data.children [0] .data.children [0]
どのように私は、これらの文字列配列のケースを扱うことができますか?
ブレンダン・ウェイドマホーニー:
後半の答えのために申し訳ありませんが、右方向エムレで私を導いてくれてありがとう!
私は、カスタムメソッド、getGsonAdaptedDataで仕事にGsonBuilderを取得することになりました。
バックグラウンドスレッドでJSONレスポンスを取得した後:
...
Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, (JsonDeserializer<Data>) (arg0, arg1, arg2) -> {
JsonObject dataJsonObject = arg0.getAsJsonObject();
Data data = new Gson().fromJson(dataJsonObject, Data.class);
return RedditUtils.getGsonAdaptedData(dataJsonObject.get("children").getAsJsonArray(), data);
}).create();
final Feed responseSubredditFeed = gson.fromJson(jsonString, Feed.class);
...
RedditUtils.getGsonAdaptedData
// JSON returned for Reddit comments can contain two types of arrays named "children"
// This method checks to see if we were given a Children array or String array
// JSON member "replies" is similar, and can be found in the Data of some Children
// If the method finds a nested "children" array, it recursively adapts its Data
public static Data getGsonAdaptedData(JsonArray childrenJsonArray, Data data) {
if (childrenJsonArray.size() > 0) {
Gson gson = new Gson();
if (childrenJsonArray.get(0).isJsonObject()) {
data.setChildrenList(gson.fromJson(childrenJsonArray,
new TypeToken<List<Children>>() {
}.getType()));
// Loops through every Data object in the array looking for children and replies
for (int i = 0; i < childrenJsonArray.size(); i++) {
JsonObject nestedDataJsonObject = childrenJsonArray.get(i).getAsJsonObject().get("data").getAsJsonObject();
if (nestedDataJsonObject.has("children")) {
getGsonAdaptedData(nestedDataJsonObject.get("children").getAsJsonArray(), data.getChildren().get(i).getData());
} else if (nestedDataJsonObject.has("replies") && nestedDataJsonObject.get("replies").isJsonObject()) {
data.getChildren().get(i).getData().setRepliesObject(gson.fromJson(nestedDataJsonObject.get("replies"),
new TypeToken<Replies>() {
}.getType()));
getGsonAdaptedData(nestedDataJsonObject.get("replies").getAsJsonObject().get("data").getAsJsonObject().get("children").getAsJsonArray(), data.getChildren().get(i).getData());
}
}
} else {
data.setRepliesList(gson.fromJson(childrenJsonArray,
new TypeToken<List<String>>() {
}.getType()));
}
}
return data;
}