I have a number of classes that implement a single interface type. I want to write a custom deserializer to be able to handle some special case with the json I have to deserialize. Is this possible with google gson? Here is the sample code I have so far:
Class Type:
public class MyClass implements MyInterface {
.......
}
Deserializer
public class ResponseDeserializer implements JsonDeserializer<MyInterface>
{
private Gson fGson;
public ResponseDeserializer()
{
fGson = new Gson();
}
@Override
public MyInterface deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
String jsonString = json.toString();
if(jsonString.substring(0, 0).equals("["))
{
jsonString = "{ \"parameter\":" + jsonString + "}";
}
return context.deserialize(json, typeOfT);
}
}
register and call fromJson method:
@Override
public <T extends MyInterface> T createResponse(Class<T> responseType)
{
T returnObject = new GsonBuilder().registerTypeAdapter(MyInterface.class, new ResponseDeserializer())
.create().fromJson(getEntityText(), responseType);
return returnObject;
}
thanks for the help in advance