GSON Custom parsing

南楼画角 提交于 2019-12-12 04:55:48

问题


Hi I'm writing an android App that interfaces with an external webservice that outputs JSON formatted info.

I'm using GSON to generate POJOs for the output of the web service, but I'm having a problem with this entity:

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"
 }
}

Using a service like http://www.jsonschema2pojo.org/ I was able to generate a POJO that matches to this output like this:

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;
 ....
}

However I would like to tweak this a little bit and instead of having an object for _1, _2, etc, I would like to have an array or list containing all data, like this:

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;
   ....
}

How can I accomplish this, without manually parsing the JSON file?


回答1:


Register a TypeAdapter for your Players class. In the deserialize method iterate over keys in the json and add them to an ArrayList. That should work, I think. An example in pseudo-code:

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();


来源:https://stackoverflow.com/questions/28500024/gson-custom-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!