I have used Gson to serialize Map<String,Object> to json, but I encountered some problems, can you tell me why this happens?
Code:
HashMap<String,Object> map = new HashMap<String, Object>(){{
this.put("test",1);
}};
HashMap<String,Object> map2 = new HashMap<>();
map2.put("test",1);
System.out.println(new Gson().toJson(map));
System.out.println(new Gson().toJson(map2));
Output:
null
{"test":1}
The way you have declared it, map
is not a HashMap, but an anonymous class. Gson is not designed to handle anonymous and inner classes.
You can check this issue, which asks about serialization of anonymous class, but it's closed, so probably there are no plans to add support for this. As you can see in the discussion, possible workaround is providing the type.
System.out.println(new Gson().toJson(map, new TypeToken<HashMap<String, Object>>(){}.getType()));
Another related discussion.