zduny
zduny

Reputation: 2541

Gson - arbitrary objects

How to deserialize this with Gson:

public class PageJson {
    private final String page;
    private final Object results;

    public PageJson(String page, Object results) {
        this.page = page;
        this.results = results;
    }

    public String getPage() {
        return page;
    }

    public Object getResults() {
        return results;
    }
}

Where results is an arbitrary object which type I can recognize after getting page value.

Upvotes: 3

Views: 274

Answers (1)

Alex P
Alex P

Reputation: 1751

You can implement JsonDeserializer and register it in Gson:

public class PageJsonDeserializer implements JsonDeserializer<PageJson> {

   @Override
    public PageJson deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

         final JsonObject pageJsonObj = json.getAsJsonObject();
         String page = pageJsonObj.get("page").getAsString();
         JsonObject results = pageJsonObj.get("results").getAsJsonObject();

         //TODO: Decide here according to page which object to construct for results
         //and then call the constructor of PageJson

         //return constructed PageJson instance
    }        
}

You will need to register type adapter to Gson.

Gson gson = new GsonBuilder().registerTypeAdapter(PageJson.class, new PageJsonDeserializer()).create();

Upvotes: 2

Related Questions