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

Gson toJson HashMap put #2402

Closed
ChiBenshuo opened this issue May 30, 2023 · 1 comment
Closed

Gson toJson HashMap put #2402

ChiBenshuo opened this issue May 30, 2023 · 1 comment
Labels

Comments

@ChiBenshuo
Copy link

Gson version 2.10.1

Java version 17

description

`
System.out.println(new Gson().toJson(new HashMap<String, String>() {{
put("a", "b");
}})); // print null

    String map2 = new Gson().toJson(new HashMap<String, String>() {{
        put("a", "b");
    }});
    System.out.println(map2); // print null

    Map<String, String> map = new HashMap<>();
    map.put("a", "b");
    System.out.println(new Gson().toJson(map)); // print {"a":"b"}

`

@ChiBenshuo ChiBenshuo added the bug label May 30, 2023
@eamonnmcmanus
Copy link
Member

See #2023 and #298, among others. The short summary, to quote #298: "Don't use double brace initialization. It prevents serialization and Gson is designed for symmetric serialization and serialization."

Since you're using Java 17, Map.of or Map.ofEntries are much better alternatives.

@eamonnmcmanus eamonnmcmanus closed this as not planned Won't fix, can't repro, duplicate, stale May 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants