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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With