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'
}
Hello, i've found bug in RuntimeTypeAdapterFactory (line185, method create(), and resolved this issue, need replace
if (type.getRawType() != baseType)
with
if (null == type || !baseType.isAssignableFrom(type.getRawType()))
Then RuntimeTypeAdapterFactory works well as expected.
Full version: RuntimeTypeAdapterFactory
@ultraon Thanks, just ran into this issue today and your answer solved it.
Thank you. This solved an issue I had with serializing an subtype with a custom serializer and type field not being included. This fix should really get pulled into the codebase.
Try replacing this:
final String jsonStr = mGson.toJson(new Child());
With this:
final String jsonStr = mGson.toJson(new Child(), Base.class);
@swankjesse i guess thats where the problem is. i tried using the same it didnt work. Am about to try with the solution which @ultraon has given.
@swankjesse What if you want to serialize a List
The solution proposed by @ultraon have worked for me as well. I agree with @calrsom, this should be added in the codebase with the proper tests.
Most helpful comment
Hello, i've found bug in RuntimeTypeAdapterFactory (line185, method create(), and resolved this issue, need replace
with
Then RuntimeTypeAdapterFactory works well as expected.
Full version: RuntimeTypeAdapterFactory