why do two seemingly identical hashmaps have different behavior when serialized by gson?

dQw4w9WyXcQ :

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
Greg Kopff :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35809&siteId=1