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

  • A+
Category:Languages

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 

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: