我正在使用google gson-2.2.1库来解析JSON的大响应。
我必须解析结构可能不同的JSON响应。
第一种情况,当响应包含多个团队时:
"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;
}
问题在于,当我只有一个{J}对象时,我不能使用ArrayList<PlayerTeams>
。
Gson可以识别JSON响应的静态格式。我可以通过检查“团队”密钥是JsonArray
还是JsonObject
的实例来动态跟踪完整响应,但如果有更好的解决方案可能会很好。
编辑: 如果我的反应更有活力..
"Details":{
"Role":"abc",
"Team":
{
"active":"yes",
"primary":"yes",
"content":"abc"
"Test":
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
}
}
在我编辑的问题中,我遇到了问题,而我的回复更具动态性。Team
和Test
可能是JsonArray
或JsonObject
..这真的在骚扰我因为某些时候Test
对象可能在数组时有更多数据,可能在单个数据时对象,无数据时为字符串。回应没有一致性。
答案 0 :(得分:1)
您需要一个类型适配器。此适配器将能够区分正在进行的格式,并使用正确的值来实例化正确的对象。
您可以通过以下方式执行此操作:
JsonSerializer<List<Team>>, JsonDeserializer<List<Team>>
的类来实现您自己的类型适配器,当然,如果您需要序列化它,则需要JsonSerializer
。GsonBuilder
注册类型适配器,例如:new GsonBuilder().registerTypeAdapter(new TypeToken<List<Team>>() {}.getType(), new CoupleAdapter()).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);
}
}