我遇到的问题是我正在解析的API为大小为1的ARRAY返回一个OBJECT.
例如,有时API会响应:
{
"monument": [
{
"key": 4152,
"name": "MTS - Corporate Head Office",
"categories": {},
"address": {}
},
{
"key": 4151,
"name": "Canadian Transportation Agency",
"categories": {},
"address": {}
},
{
"key": 4153,
"name": "Bank of Montreal Building",
"categories": {},
"address": {}
}
],
}
但是,如果纪念碑阵列只有1个项目,它就变成了一个OBJECT(注意缺少[]括号),如下所示:
{
"monument": {
"key": 4152,
"name": "MTS - Corporate Head Office",
"categories": {},
"address": {}
}
}
如果我像这样定义我的模型,只返回一个项目时会出错:
public class Locations {
public List<Monument> monument;
}
如果只返回一个项目,我会收到以下错误:
Expected BEGIN_OBJECT but was BEGIN_ARRAY ...
如果我像这样定义我的模型:
public class Locations {
public Monument monument;
}
并且API返回ARRAY我得到了相反的错误
Expected BEGIN_ARRAY but was BEGIN_OBJECT ...
我无法在模型中定义多个具有相同名称的项目.
我该如何处理这个案子?
注意:我无法对API进行更改.
解决方法:
作为我之前回答的补充,这是使用TypeAdapter的解决方案.
public class LocationsTypeAdapter extends TypeAdapter<Locations> {
private Gson gson = new Gson();
@Override
public void write(JsonWriter jsonWriter, Locations locations) throws IOException {
gson.toJson(locations, Locations.class, jsonWriter);
}
@Override
public Locations read(JsonReader jsonReader) throws IOException {
Locations locations;
jsonReader.beginObject();
jsonReader.nextName();
if (jsonReader.peek() == JsonToken.BEGIN_ARRAY) {
locations = new Locations((Monument[]) gson.fromJson(jsonReader, Monument[].class));
} else if(jsonReader.peek() == JsonToken.BEGIN_OBJECT) {
locations = new Locations((Monument) gson.fromJson(jsonReader, Monument.class));
} else {
throw new JsonParseException("Unexpected token " + jsonReader.peek());
}
jsonReader.endObject();
return locations;
}
}