【发布时间】:2018-07-25 19:13:55
【问题描述】:
我正在从 Reddit API 检索 cmets。该模型是线程化的,因此每个评论都可以在内部有一个评论列表,名为 replies。下面是一个 JSON 响应的示例:
[
{
"kind":"Listing",
"data":{
"children":[
{
"data":{
"body":"comment",
"replies":{
"kind":"Listing",
"data":{
"children":[
{
"data":{
"body":"reply to comment",
"replies":""
}
}
]
}
}
}
}
]
}
}
]
这是我使用 POJO 建模的方法。上面的响应将被视为 CommentListings 列表。
public class CommentListing {
@SerializedName("data")
private CommentListingData data;
}
public final class CommentListingData {
@SerializedName("children")
private List<Comment> comments;
}
public class Comment {
@SerializedName("data")
private CommentData data;
}
public class CommentData {
@SerializedName("body")
private String body;
@SerializedName("replies")
private CommentListing replies;
}
注意底层的 CommentData POJO 如何引用另一个名为“回复”的 CommentListing。
此模型一直有效,直到 GSON 到达没有回复的最后一个子 CommentData。 API 提供的是空字符串,而不是提供 null。自然,这会导致 GSON 异常,它需要一个对象但找到一个字符串:
"replies":""
应为 BEGIN_OBJECT,但为 STRING
我尝试在 CommentData 类上创建自定义反序列化器,但由于模型的递归性质,它似乎没有达到模型的底层。我想这是因为我使用单独的 GSON 实例来完成反序列化。
@Singleton
@Provides
Gson provideGson() {
Gson gson = new Gson();
return new GsonBuilder()
.registerTypeAdapter(CommentData.class, new JsonDeserializer<CommentData>() {
@Override
public CommentData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject commentDataJsonObj = json.getAsJsonObject();
JsonElement repliesJsonObj = commentDataJsonObj.get("replies");
if (repliesJsonObj != null && repliesJsonObj.isJsonPrimitive()) {
commentDataJsonObj.remove("replies");
}
return gson.fromJson(commentDataJsonObj, CommentData.class);
}
})
.serializeNulls()
.create();
}
如何强制 GSON 返回 null 而不是 String,这样它就不会尝试将 String 强制到我的 POJO 中?或者,如果这不可能,手动协调数据问题?如果您需要其他上下文或信息,请告诉我。谢谢。
【问题讨论】: