如何处理,可以在改造Android上的数组或对象的参数? [英] How to handle parameters that can be an ARRAY or OBJECT in Retrofit on Android?
问题描述
我有一个问题,即API我解析返回一个对象尺寸为1的数组。
I'm having an issue where the API I'm parsing returns an OBJECT for an ARRAY of size 1.
例如,有时API将响应:
For example, sometimes the API will respond with:
{
"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个项目就成为一个对象(注意缺少 []
括号内),像这样:
However, if the monument
array has only 1 item it becomes an OBJECT (note the lack of []
brackets) like so:
{
"monument": {
"key": 4152,
"name": "MTS - Corporate Head Office",
"categories": {},
"address": {}
}
}
如果我定义我的模型是这样,我会当只有一个单一的项目则返回一个错误:
If I define my models like this, I will get an error when only a single item is returned:
public class Locations {
public List<Monument> monument;
}
如果只有一个项目被退回我收到以下错误:
If only a single item is returned I get the following error:
Expected BEGIN_OBJECT but was BEGIN_ARRAY ...
如果我定义我的模型像这样:
And if I define my model like so:
public class Locations {
public Monument monument;
}
和API返回数组我得到相反的错误
and the API returns an ARRAY I get the opposite error
Expected BEGIN_ARRAY but was BEGIN_OBJECT ...
我无法定义在我的模型相同名称的多个项目。 我该如何处理这种情况?
I cannot define multiple items with the same name in my model. How can I handle this case?
注:我不能进行更改API
Note: I cannot make changes to the API.
推荐答案
作为一个补充,我的previous答案,这里是用一个解决方案 TypeAdapter
。
As a complement to my previous answer, here's a solution using a 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;
}
}
这篇关于如何处理,可以在改造Android上的数组或对象的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!