15

input:

public static void main(String[] args) {

    final String key = "some key";
    final String value = "some value";

    Map<String, String> map1 = new HashMap<String, String>(){{put(key, value);}};
    System.out.println(new Gson().toJson(map1) + " " + map1.get(key));

    Map<String, String> map2 = new HashMap<>();
    map2.put(key, value);
    System.out.println(new Gson().toJson(map2) + " " + map2.get(key));
}

output:

null some value
{"some key":"some value"} some value

Process finished with exit code 0
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
dQw4w9WyXcQ
  • 125
  • 1
  • 8
  • 6
    Don't abuse ["double brace initialization"](https://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization)... – user202729 Aug 10 '18 at 06:40
  • also related: https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java – Hulk Aug 10 '18 at 09:36

1 Answers1

22

For map1, you have created an anonymous subclass. Assuming your class that contains main() is called ExampleClass, then:

System.out.println(map1.getClass().getName())

prints out:

ExampleClass$1

Whereas printing the class for map2 yields:

java.util.HashMap

As to the exact reason that Gson doesn't serialise it - Gson uses the classname to lookup a converter. If you instead serialise it using:

System.out.println(new Gson().toJson(map1, HashMap.class));

... it works as expected.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • 2
    [Relevant documentation](https://google.github.io/gson/apidocs/com/google/gson/Gson.html#toJson-java.lang.Object-). – VGR Aug 10 '18 at 04:35