Deserializing polymorphic JSON with Gson throwing exception

I think that using your own userType without @Expose annotation will do the trick

Regads


Well, after some time digging I found out that the problem is not actually deserializing, the problem comes when serializing and having a RuntimeTypeFactory registered as described in the question. If you register a runtimeTypeAdapterFactory and use the same field name to define the class type in the factory and in your pojo, json resulting from serializing pojo to json using GSON with the RuntimeTypeAdapterFactory for a SpecialUser for example will be:

{  
  "user":{  
      "userType":"SPECIAL",
      "email":"[email protected]",
      "name":"Albert"
      "userType":"SPECIAL"
  }
}

This will result in the exception described:

com.google.gson.JsonParseException: cannot serialize com.mobile.model.entities.v2.common.User because it already defines a field named userType

because de field userType is repeated in the json due to GSON serializer, which will automatically add a field as declared in the RuntimeTypeAdapterFactory registered for the class BaseUser.