How Do I Put Generic Type For Gson's Typetoken?
EDIT After experimenting for a while, I know my problem is. I can't put generic type inside TypeToken (Type type = new TypeToken>(){}.getType();). Whe
Solution 1:
You have to specify the Type
explicitly. There's type erasure in Java, which basically means that at runtime all instances of T
are replaced with Object
.
You should either write three different deserializers for different response types(POJOA
, POJOB
, POJOC
) or write a generic one. Something like this should work:
publicclassGenericConverterimplementsJsonDeserializer<CustomResponse<?>> {
private Type typeOfResponse;
publicGenericConverter(Type typeOfResponse) {
this.typeOfResponse = typeOfResponse;
}
public CustomResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
CustomResponseresponse=newCustomResponse();
response.setResponse(ctx.deserialize(json.getAsJsonObject().get("response"), typeOfResponse));
return response;
}
}
And register it appropriately:
gsonBuilder.registerTypeAdapter(new TypeToken<CustomResponse<POJOA>>(){}.getType(),
new GenericConverter(POJOA.class));
gsonBuilder.registerTypeAdapter(new TypeToken<CustomResponse<POJOB>>(){}.getType(),
new GenericConverter(POJOB.class));
gsonBuilder.registerTypeAdapter(new TypeToken<CustomResponse<POJOC>>(){}.getType(),
new GenericConverter(POJOC.class));
Post a Comment for "How Do I Put Generic Type For Gson's Typetoken?"