这是我的类,它代表来自服务器的 json 结构:
ArrayList<EventWebInterface.Element> element;
public class Element {
String id;
String subtitle;
String name;
String subline;
String count;
}
这是结构:
{
element: [
{
id: "1985",
subtitle: "01. August 2013 18:30 Uhr | Berlin",
name: "blabla....",
subline: "blabla....",
category_id: ""
},
{
id: "1962",
subtitle: "07. August 2013 19:00 Uhr | Cloppenburg",
name: "blabla...",
subline: "blabla....",
category_id: ""
},
{ ...
但有时该结构只有一个元素,例如:
{
element: {
id: "1985",
subtitle: "01. August 2013 18:30 Uhr | Berlin",
name: "blabla...",
subline: "blabla....",
category_id: ""
}
}
对于这种情况,我有一个 gson 的类型适配器,如下所示:
public class EventWebTypeAdapter implements JsonDeserializer<List<EventWebInterface.Element>> {
public List<EventWebInterface.Element> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<EventWebInterface.Element> vals = new ArrayList<EventWebInterface.Element>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add((EventWebInterface.Element) ctx.deserialize(e, EventWebInterface.Element.class));
}
} else if (json.isJsonObject()) {
vals.add((EventWebInterface.Element) ctx.deserialize(json, EventWebInterface.Element.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
public Type getType(){
return new TypeToken<List<EventWebInterface.Element>>() {}.getType();
}
}
我这样使用它:
EventWebTypeAdapter mTypeAdapter = new EventWebTypeAdapter();
Type mType = mTypeAdapter.getType();
Class<I> mInterface = EventWebInterface.class
Gson gson = new GsonBuilder().registerTypeAdapter(mType, mTypeadapter).create();
dataObject = gson.fromJson(data, mInterface);
但是适配器不起作用。它给了我:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
我不明白,为什么它不起作用...... =(