Skip to content

Serialization issue with RuntimeTypeAdapterFactory #712

@ultraon

Description

@ultraon

Hello, i found after serialization root object 'type' field is not injected, for inner object 'type' fields are added. Example:

public class Test {
  public class Base {
    String baseField = "base";
  }
  public class Child extends Base {
    String childField = "child";
    Base baseInChild = new Base();
  }

  public static void main(String[] args) {
        Gson mGson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapterFactory(
                        RuntimeTypeAdapterFactory.
                                of(Base.class).
                                registerSubtype(Base.class).
                                registerSubtype(Child.class)
                )
                .create();

        final String jsonStr = mGson.toJson(new Child());
        final Base child = mGson.fromJson(jsonStr, Base.class); // ERROR HERE: "Caused by: com.google.gson.JsonParseException: cannot deserialize class mypackage.Test$Base because it does not define a field named type"
  }
}

and json output after serialization:

{
  "baseInChild": {
    "type": "Base",
    "baseField": "base"
  },
  "childField": "child",
  "baseField": "base"
//in this place should be generated field 'type' with value 'Child'
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions