简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM