Gson: Serialize a HashMap, result is null

Created on 5 Feb 2018  路  3Comments  路  Source: google/gson

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 ?

Most helpful comment

Gson doesn't serialize anonymous classes. Use Map.of to create maps, not subclasses.

All 3 comments

Gson doesn't serialize anonymous classes. Use Map.of to create maps, not subclasses.

@JakeWharton @Dhirajpandit THX

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kramer picture kramer  路  26Comments

adiantek picture adiantek  路  23Comments

GoogleCodeExporter picture GoogleCodeExporter  路  25Comments

kdehairy picture kdehairy  路  43Comments

GoogleCodeExporter picture GoogleCodeExporter  路  32Comments