Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson - arbitrary objects

Tags:

java

json

gson

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.

like image 391
zduny Avatar asked Nov 22 '25 00:11

zduny


1 Answers

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();
like image 89
Alex P Avatar answered Nov 23 '25 13:11

Alex P