the code is
Map map1 = new HashMap() {{
put("a", "1");
put("b", "2");
put("c", "3");
}};
String json1 = new Gson().toJson(map1);
Map map2 = new HashMap();
map2.put("a", "1");
map2.put("b", "2");
map2.put("c", "3");
String json2 = new Gson().toJson(map2);
System.out.println("json1 = " + json1); // null
System.out.println("json2 = " + json2); // {"a":"1","b":"2","c":"3"}
System.out.println("Is Equals: " + map1.equals(map2)); // true
the result is
json1 = null
json2 = {"a":"1","b":"2","c":"3"}
Is Equals: true
Why the json1 is null ?
Gson doesn't serialize anonymous classes. Use Map.of to create maps, not subclasses.
@JakeWharton @Dhirajpandit THX
Most helpful comment
Gson doesn't serialize anonymous classes. Use
Map.ofto create maps, not subclasses.