Adam Matan
Adam Matan

Reputation: 136201

Serializing a map with different key types to json

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?

Upvotes: 1

Views: 1203

Answers (1)

Boris Strandjev
Boris Strandjev

Reputation: 46943

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:

{
    "100"  : ["New York"], 
    "200"  : ["Geneva", "Tel Aviv"],
    "300"  : ["Rome", "Paris", "Atlanta"],
    "400a" : ["Los Angeles"]
}

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 in Map<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.

Upvotes: 2

Related Questions