Serialization issue with RuntimeTypeAdapterFactory
See original GitHub issueHello, 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'
}
Issue Analytics
- State:
- Created 8 years ago
- Comments:8
Top Results From Across the Web
Gson's RuntimeTypeAdapterFactory isn't serializing the type
Thanks to help from a contributor to the public repository, the problem was the serialization step needed to include the base type.
Read more >Goodbye RuntimeTypeAdapterFactory. Polymorphic ...
Polymorphic serialization using kotlinx.serialization ... With Gson deserializing this is pretty easy using a RuntimeTypeAdapterFactory .
Read more >Developers - Serialization issue with RuntimeTypeAdapterFactory -
Hello, i found after serialization root object 'type' field is not injected, for inner object 'type' fields are added. Example:
Read more >Practical Gson — How to Deserialize a List of Polymorphic ...
Finally, I found the RuntimeTypeAdapterFactory class, which solves the problem quite nicely. Gson Series Overview. Mapping; Configuration ...
Read more >RuntimeTypeAdapterFactory (Gson Extras version ... - javadoc.io
This class addresses this problem by adding type information to the serialized JSON and honoring that type information when the JSON is deserialized:...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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
Try replacing this:
With this: