【发布时间】:2020-04-01 14:17:22
【问题描述】:
最近在制作一个使用 Rest API 的项目时,我决定使用 Retrofit。然而,在向所述 API 发送 GET 请求时,我遇到了一个问题,尽管有人提出了类似的问题,但我觉得无法找到解决方案。
我遇到的问题(我相信这就是问题所在)是 API 给出的响应会根据给定的输入而变化,因此我的 POJO 并不总是匹配。更具体地说,我有时会得到一个对象而不是列表作为字段。这一行很好地描述了错误的要点:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 250 column 20 path $.LocationList.CoordLocation
从 API 收到的 Json 大部分时间看起来像这样:
{
"LocationList": {
"StopLocation": [
{
"name": String,
"x": String,
"y": String,
"id": String
},
...
],
"CoordLocation": [
{
"name": String,
"x": String,
"y": String,
"type": String
},
...
]
}
}
}
这一切都很好,因为我的 LocationList POJO 被定义为具有 CoordLocations 和 StopLocations 的列表。但是,当某些输入的 API 仅响应 CoordLocation 的单个 StopLocation 时,由于收到的 Json 是单个对象而不是具有单个对象条目的数组,因此一切都会崩溃:
{
"LocationList": {
"StopLocation": [
{
"name": String,
"x": String,
"y": String,
"id": String
},
...
],
"CoordLocation": {
"name": String,
"x": String,
"y": String,
"type": String
}
}
}
所以我的问题是如何解决这个问题?到目前为止,我已经看到有人建议自定义 TypeAdapters 和 Deserializers,但每次我尝试遵循解决方案时,我都会在某个时候碰壁,因为情况略有不同,而且我对所有与 API 相关的东西都很陌生。
【问题讨论】:
-
作为最佳实践,CoordLocation 必须始终具有服务器发送的对象数组。在应用程序端,检查大小是否为 1,以便执行必要的操作。
-
我很清楚这是服务器应该如何响应的,但遗憾的是它是一个第 3 方 API,因此更改响应是不可能的。
标签: android json rest retrofit2