amenijemai / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Serializable should be treated similar to Object #544

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I have a generic object field which is declared as Serializable. Using 
fromJson() throws an exception. Instead, it could be treated as an Object, and 
later checked if the resulting type implements Serializable before throwing an 
exception.

    public static class AttrData implements Serializable
    {
        IdDisplay id;
        AttrDef def;
        Serializable value;
    }

...
Caused by: java.lang.RuntimeException: Unable to invoke no-args constructor for 
interface java.io.Serializable. Register an InstanceCreator with Gson for this 
type may fix this problem.
    at com.google.gson.internal.ConstructorConstructor$8.construct(ConstructorConstructor.java:166)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:163)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.Gson.fromJson(Gson.java:755)
    at com.google.gson.Gson.fromJson(Gson.java:721)
    at com.google.gson.Gson.fromJson(Gson.java:670)
    at com.google.gson.Gson.fromJson(Gson.java:642)

Original issue reported on code.google.com by bors...@gmail.com on 3 Dec 2013 at 1:07

GoogleCodeExporter commented 9 years ago
You can register a TypeAdapterFactory which forces Serializable types to be 
deserialized as Objects:

@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  if (Serializable.class.equals(type.getRawType())) {
    return (TypeAdapter<T>) gson.getAdapter(Object.class);
  }
  return null;
}

Original comment by j...@squareup.com on 9 Aug 2014 at 6:00