hamad32
hamad32

Reputation: 197

Gson custom deserializer for generic types

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

Upvotes: 1

Views: 1384

Answers (1)

durron597
durron597

Reputation: 32323

First of all, registerTypeAdapter() is not covariant; if you want to link a TypeAdapter to an interface, you have to use a TypeAdapterFactory. See: How do I implement TypeAdapterFactory in Gson?

Secondly, why do you think that [{...},{...},{...}] is not valid Json? Of course it is:

{  
   "foo":[  
      {  
         "type":"bar"
      },
      {  
         "type":"baz"
      }
   ]
}

This is a mapping of key foo an array of objects, with one member variable. Gson would automatically deserialize it with the following POJOs:

public class MyObject {
    List<TypedObject> foo;
}

public class TypedObject {
    String type;
}

Beyond that, I can't help you more without knowing your specific Json string. This (especially that first link) should be enough to get started, however.

Upvotes: 1

Related Questions