Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Anonymous Map initialization does not serialize correctly. #762

Closed
f2prateek opened this issue Dec 30, 2015 · 2 comments
Closed

Anonymous Map initialization does not serialize correctly. #762

f2prateek opened this issue Dec 30, 2015 · 2 comments

Comments

@f2prateek
Copy link

Here's a sample to demonstrate the issue:

HashMap<String, String> context = new HashMap<String, String>() {{
  put("city", "Toronto");
}};
Gson gson = new Gson();
System.out.println("context - " + context);
System.out.println("JSON - " + gson.toJson(context));

Output:

context - {City=Toronto}
JSON - null

Initializing the map with the code below works fine:

HashMap<String, String> context = new HashMap<String, String>();
context.put("city", "Toronto");

While the first method is obviously a wasteful way to initialize a map, is this serialization behaviour for anonymous initialization expected? If so, can you clarify why?

The closest reference I could find to this was #298, which is about fields in anonymous classes.

@swankjesse
Copy link
Collaborator

This is working as designed. Anonymous classes cannot be deserialized & for symmetry we forbid serialization also. You should get the expected result if you hint the actual Map.class type.

@f2prateek
Copy link
Author

Ah so serialization is forbidden for anonymous classes in general, not just fields declared in anonymous classes!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants