GSON自定义解析

GSON Custom parsing

您好,我正在编写一个 android 应用程序,它与输出 JSON 格式信息的外部网络服务接口。

我正在使用 GSON 为 Web 服务的输出生成 POJO,但我遇到了这个实体的问题:

player: {
 1: {
   number: "6",
   name: "Joleon Lescott",
   pos: "D",
   id: "2873"
 },
 2: {
   number: "11",
   name: "Chris Brunt",
   pos: "D",
   id: "15512"
 },
 3: {
   number: "23",
   name: "Gareth McAuley",
   pos: "D",
   id: "15703"
 }
}

使用 http://www.jsonschema2pojo.org/ 之类的服务,我能够生成与此输出匹配的 POJO,如下所示:

public class Player {

   @SerializedName("1")
   @Expose
   private com.example._1 _1;
   @SerializedName("2")
   @Expose
   private com.example._2 _2; 
   .....
}

public class _1 {

 @Expose
 private String name;
 @Expose
 private String minute;
 @Expose
 private String owngoal;
 @Expose
 private String penalty;
 @Expose
 private String id;
 ....
}

但是我想稍微调整一下,而不是为 _1、_2 等创建一个对象,我想要一个包含所有数据的数组或列表,如下所示:

public class Players{

   private List<Player> players;

}

public class Player{
   @Expose
   private int position;
   @Expose
   private String name;
   @Expose
   private String minute;
   @Expose
   private String owngoal;
   @Expose
   private String penalty;
   @Expose
   private String id;
   ....
}

如何在不手动解析 JSON 文件的情况下完成此操作?

为您的 Players class 注册一个 TypeAdapter。在 deserialize 方法中迭代 json 中的键并将它们添加到 ArrayList 中。我认为这应该有效。伪代码示例:

class PlayersAdapter implements JsonDeserializer<Players> {
    public Players deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        List<Player> players = new ArrayList<>();
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            players.add(ctx.deserialize(entry.getValue(), Players.class));
        }
        return new Players(players);
    }
}


// ...
Gson gson = new GsonBuilder()
        .registerTypeAdapter(Players.class, new PlayersAdapter())
        .create();