Description
Describe the feature
Gson should allow serialization of anonymous classes, the reason is that the user shouldn't care about the implementation of the code that generates the objects they are using.
For example, this code that only uses Guava and Gson looks fine and users may expect it to print ["a", "b"]
:
System.out.println(gson.toJsonTree(Sets.union(
ImmutableSet.of("a"),
ImmutableSet.of("b"))));
But actually, that code prints null
, totally unexpected to a user that is not familiar with the implementation of Sets.union
(that function returns an instance of an anonymous class).
Additional context
I think this feature is well deserved because of the amount of confusion that has been around the lack of it. If we do a Google search we find several people who were caught by this issue:
- Allow serialization of anonymous and local classes #298
- Anonymous Map initialization does not serialize correctly. #762
- Unable to use GSON to serialize anonymous class javalin/javalin#288
- https://stackoverflow.com/questions/10746278/serializing-anonymous-classes-with-gson
- https://stackoverflow.com/questions/26791752/convert-anonymous-java-object-types-to-json-using-gson
- https://stackoverflow.com/questions/55622921/custom-gson-serializer-for-anonymous-classes
And the list goes on and on.
I think what aggravates the lack of this feature it he way Gson silently serializes those instances to null
, which is a source of silent bugs.
NOTE:
Deserialization of anonymous inner classes is problematic, I'm not asking for that to be supported. This feature request deals only with serialization.
Possible workarounds
I've seen suggested workarounds like:
gson.toJsonTree(union, TypeToken<Set<String>>(){}.getType());.
But notice that only works in the most simple of cases, but it doesn't work in cases where we have a Map with values of different anonymous classes:
ImmutableMap.of(
"key1", Sets.union(...),
"key2", new HashSet(){},
"key3", new MyRecord(){}
);
As there is not a single TokenType I can accommodate for that disparity of values and that will behave as expected. Moreover, sometimes the values are not known at compile time (in designing APIs, the values can be anything the user passes to us, and its out of our control).