Skip to content

Allow serialization of anonymous classes #1510

@dwilches

Description

@dwilches

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:

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).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions