2

我正在使用 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;
}

ArrayList<PlayerTeams>问题是当我只有其中一个并且它作为 JsonObject 返回时我不能使用。

Gson 可以识别 JSON 响应的静态格式。我可以通过检查“团队”键是否是JsonArray或的实例来动态跟踪完整响应,JsonObject但如果有更好的解决方案可用,那就太好了。

编辑: 如果我的反应更动态..

"Details":{

       "Role":"abc",
       "Team":
          {
             "active":"yes",
             "primary":"yes",
             "content":"abc"
             "Test":
             {
                 "key1":"value1",
                 "key2":"value2",
                 "key3":"value3"
             }
          }
}

在我编辑的问题中,我遇到了问题,而我的响应更加动态..可以是或..它真的困扰着我,因为有时Team对象可能会在更多数据时排列,在单个数据时可能会反对,在没有数据时可能会出现字符串。响应没有一致性。TestJsonArrayJsonObjectTest

4

1 回答 1

1

你需要一个类型适配器。该适配器将能够区分即将到来的格式并使用正确的值实例化正确的对象。

您可以通过以下方式做到这一点:

  1. 通过创建一个实现你自己的类型适配器来实现JsonSerializer<List<Team>>, JsonDeserializer<List<Team>>,当然JsonSerializer只是在你需要在这件事上序列化它的情况下才需要。
  2. 注册类型适配器给你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);
    }
}
于 2012-07-21T12:28:07.937 回答