Julian Suarez
Julian Suarez

Reputation: 4521

GSON Custom parsing

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?

Upvotes: 0

Views: 1189

Answers (1)

Egor Neliuba
Egor Neliuba

Reputation: 15054

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

Upvotes: 3

Related Questions