1

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

hamad32
  • 187
  • 1
  • 1
  • 10
  • `handle some special case` What do you mean? – MCHAppy Apr 28 '15 at 22:44
  • I have a json string that has format like this: "[{...}, {...}, ....]" which I think is something I cant deserialize because is it not a valid JSON. So I would like to be able to convert it into something like {"product":[{...}, {...}, ....]} I realize I dont need a deserializer to acheive this but I would like to have one.... – hamad32 Apr 29 '15 at 00:49

1 Answers1

1

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.

Community
  • 1
  • 1
durron597
  • 31,968
  • 17
  • 99
  • 158