Convert Hashmap to JSON using GSON

I have a HashMap<String, String> where strings of values โ€‹โ€‹can be long or double. For example, 123.000 can be stored as 123 (stored for how long) and 123.45 as 123.45 (double).

Take these two hash map values:

("one", "123"); (two, 123.45)

When I convert the above map to a JSON string, the JSON values โ€‹โ€‹should not have double quotes, for example

Expected: {"one": 123, "two": 123.45}

Actual: {"one": "123", "two": "123.45"}

This is my code below:

 String jsonString = new Gson().toJson(map) 

I prefer the solution using GSON, but I also welcome the use of a different library or libraries.

+7
java json gson
source share
1 answer

For Gson, you get the following conversions:

 Map<String, Double> -> {"one": 123, "two":123.45} Map<String, Number> -> {"one": 123, "two":123.45} Map<String, String> -> {"one": "123", "two": "123.45"} 

Basically, there is no way to get Gson to automatically convert your strings to numeric values. If you want them to appear as numeric (i.e., without quotes), you need to save the corresponding data type on the map, Double or Number .

In addition, Json has only a limited number of primitive types; it stores a string or a number. The numerical value does not distinguish between Integer , Long , Double , etc., Therefore, I am not sure why you are trying to distinguish them. Once it is saved as Json, they will all be considered the same numeric type.

+4
source share

All Articles