3

Somehow new Gson().toJson() returns null when I give it an one-liner map:

Map map = new HashMap() {{ put("hei", "sann"); }};
new Gson().toJson(map);  // returns null!

All other implementations I can find works as expected:

new JSONObject(map).toString();             // returns {"hei":"sann"}
JsonOutput.toJson(map);                     // returns {"hei":"sann"}
new ObjectMapper().writeValueAsString(map); // returns {"hei":"sann"}

It works if I wrap the map:

new Gson().toJson(new HashMap(map));  // returns {"hei":"sann"}

A regular map works too:

map = new HashMap();
map.put("hei", "sann");
new Gson().toJson(map);  // returns {"hei":"sann"}

Is it a bug or a feature?

I've created a test project at https://github.com/henrik242/map2json

Relevant Gson issue: https://github.com/google/gson/issues/1080

neu242
  • 15,796
  • 20
  • 79
  • 114

0 Answers0