I have a mapping from Strings to List of Strings in Java:
"100" -> ["New York"]
"200" -> ["Geneva", "Tel Aviv"]
"300" -> ["Rome", "Paris", "Atlanta"]
"400a" -> ["Los Angeles"]
I want to convert this to JSON using gson. 99% of the keys are Integers, but typos (like 400a can occur. My desired output is:
{
100 : ["New York"],
200 : ["Geneva", "Tel Aviv"],
300 : ["Rome", "Paris", "Atlanta"],
"400a" : ["Los Angeles"]
}
Note that "400a" is a String, and 100, 200, 300 are integers.
How can I convert my map in an elegant and efficient manner?
What you are trying to do is not a valid json. See the specification: http://www.json.org/. The attribute names should always be strings, numbers are not allowed. If you then want to obtain the following json:
It is very easy of course: you either use
Map<String, String>as an input (which I believe you already do), or you can pass inMap<object, String>if you want to allow yourself to put in both string and integer values. However, they will still be serialized only as strings.