My code likes:
@Test
public void testGsonTransferMap(){
HashMap<String, Object> map = new HashMap<String, Object>() {{
put("Request", new HashMap<String ,Object>(){{
put("Data",new HashMap<String,Object>(){{
put("NWExID", "7019");
put("OrgOrderNo", "123");
put("OrgTransDate", "20170518");
}});
}});
}};
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap<String ,Object>>(){}.getType();
String gsonString = gson.toJson(map,gsonType);
System.out.println(gsonString);
}
and the output is : "{}"
so,what's wrong with my code , how should i do.
You are trying to serialize an anonymous inner class. Don't.
All other json implementations I can find seems to handle this well, while 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!
Other implementations 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 this an expected Gson feature, @NightlyNexus ?
I've created a test project at https://github.com/henrik242/map2json
Yes. This is working as intended.
This has been fixed in Gson new version, tested with gson-2.8.5.jar
what about to throw exception if anonymous inner class? (instead of returning just "null")
Running @wykCN's code with gson-2.8.5.jar (under openjdk-1.8) still returns "{}".
Using anonymous inner class is convinent and elegant, why gson doesn't support it?
Most helpful comment
All other json implementations I can find seems to handle this well, while
new Gson().toJson()returns null when I give it an one-liner map:Other implementations works as expected:
It works if I wrap the map:
A regular map works too:
Is this an expected Gson feature, @NightlyNexus ?
I've created a test project at https://github.com/henrik242/map2json