Java Android:解析大型json响应
我正在使用google库解析JSON的大型响应 我必须解析结构可能不同的JSON响应 第一种情况,当响应包含多个团队时:Java Android:解析大型json响应,java,android,json,gson,Java,Android,Json,Gson,我正在使用google库解析JSON的大型响应 我必须解析结构可能不同的JSON响应 第一种情况,当响应包含多个团队时: "Details":{ "Role":"abc", "Team":[ { "active":"yes", "primary":"yes", "content":"abc"
"Details":{
"Role":"abc",
"Team":[
{
"active":"yes",
"primary":"yes",
"content":"abc"
},
{
"active":"yes",
"primary":"yes",
"content":"xyz"
}
],
第二种情况,仅通过一个团队时:
"Details":{
"Role":"abc",
"Team":
{
"active":"yes",
"primary":"yes",
"content":"abc"
}
}
我的基类用于解析:
class Details {
public String Role;
public ArrayList<PlayerTeams> Team = new ArrayList<PlayerTeams>();
PlayerTeams Team; // when JsonObject
}
class PlayerTeams {
public String active;
public String primary;
public String content;
}
在我编辑的问题中,我面临着问题,而我的回答更具动态性。
Team
和Test
可以是JsonArray
或JsonObject
。。这真的让我很烦恼,因为有时候Test
对象可能会在多个数据时数组,可能会在单个数据时对象,没有数据时字符串。响应不一致。您需要一个类型适配器。此适配器将能够区分即将出现的格式,并使用正确的值实例化正确的对象
您可以通过以下方式完成此操作:
JsonSerializer、JsonSerializer
的类来实现您自己的类型适配器,当然,如果您也需要序列化它,那么就需要JsonSerializer
GsonBuilder
类似:new GsonBuilder().registerTypeAdapter(new-TypeToken(){}.getType(),new-coupletadapter()).create()
public List<Team> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws com.google.gson.JsonParseException {
if (json.isJsonObject()) {
return Collections.singleton(context.deserialize(json, Team.class));
} else {
return context.deserialize(json, typeOfT);
}
}
公共列表反序列化(最终JsonElement json、最终类型typeOfT、最终JsonDeserializationContext)
抛出com.google.gson.JsonParseException{
if(json.isJsonObject()){
返回Collections.singleton(context.deserialize(json,Team.class));
}否则{
反序列化(json,typeOfT);
}
}
如果阅读JSONArray而不是JSONObject,会发生什么?您是否收到任何异常或null?如果您对JsonObject使用ArrayList,Google Gson将引发异常。您可以尝试在catch块中读取JsonObject。我是否可以注册两个或更多的TypeAdapter
,以获得大响应。我试着去无限循环。因为反序列化被无限调用。我测试了
public List<Team> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws com.google.gson.JsonParseException {
if (json.isJsonObject()) {
return Collections.singleton(context.deserialize(json, Team.class));
} else {
return context.deserialize(json, typeOfT);
}
}