这是我的类,代表服务器的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的typeadapter,看起来像这样:
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
我不懂,为什么它不起作用... =(
答案 0 :(得分:3)
我自己发现你的代码有点乱,所以我无法找到错误。
我会解释从一开始我会做什么,也许你可以将它与你的代码进行比较并得到一些想法......
首先我要创建这两个类:
class Response
List<Element> element;
class Element
String id;
String subtitle;
String name;
String subline;
String count;
然后我会创建一个TypeAdapter
,我认为最简单的方法是为Response
类创建一个。类似的东西:
public class ResponseDeserializer implements JsonDeserializer<Response> {
public Response deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
JsonElement elementField = json.getAsJsonObject().get("element");
List<Element> elementList = new ArrayList<>();
if (elementField.isJsonArray()) {
for (JsonElement item : elementField.getAsJsonArray()) {
elementList.add(ctx.deserialize(item, Element.class));
}
} else if (elementField.isJsonObject()) {
elementList.add(ctx.deserialize(elementField, Element.class));
}
Response response = new Response(elementList);
return response;
}
}
然后你需要注册适配器:
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(Response.class, new ResponseDeserializer());
Gson gson = builder.create();
最终解析JSON:
Response response = gson.fromJson(data, Response.class);