Unable to deserialize with RuntimeTypeAdapterFactory, " does not define a field named type"
You need to tell gson more about the types. When serializing also the type needs to be serialized. So as the first comment by Jacob G. suggests you need the type field:
Docs for RuntimeTypeAdapterFactory.of(Class<T> baseType, String typeFieldName)
states:
Creates a new runtime type adapter using for baseType using typeFieldName as the type field name. Type field names are case sensitive.
Add it to your ParentBean
:
// Init it for serializing
// You used values like 'bean1' & 'bean2' but using class name is more generic
protected String type = getClass().getName();
According to above changes in bean type names change the building of RuntimeTypeAdapterFactory
accordingly:
RuntimeTypeAdapterFactory<ParentBean> runtimeTypeAdapterFactory =
RuntimeTypeAdapterFactory
.of(ParentBean.class, "type") // typeFieldName
.registerSubtype(Bean1.class, Bean1.class.getName())
.registerSubtype(Bean2.class, Bean2.class.getName());
Finally - when de-serailizing - the Json files need also the type information which will be serialized from the field type
so add it also fro both beans Json with correct package name:
"type":"org.example.gson.runtime.Bean1",
and
"type":"org.example.gson.runtime.Bean2",