Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

gson

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
like image 944
dQw4w9WyXcQ Avatar asked Aug 10 '18 04:08

dQw4w9WyXcQ


1 Answers

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.

like image 90
Greg Kopff Avatar answered Oct 23 '22 01:10

Greg Kopff