Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Hashmap to JSON using GSON

Tags:

java

json

gson

I have a HashMap<String, String>, where the value strings can be either a long or double. For example, 123.000 can be stored as 123 (stored as long), and 123.45 as 123.45 (double).

Take these two hashmap values:

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

When I convert the above map into a JSON string, the JSON values should not have double quotes, like

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 a solution using GSON, but using another library or libraries is also welcome.

like image 770
user3366706 Avatar asked Jul 24 '15 22:07

user3366706


1 Answers

For Gson you'll 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's no way to get Gson to automatically convert your strings to numeric values. If you want them to show up as numeric (i.e. without quotes) you need to store the appropriate datatype in the map, Double or Number.

Also, Json only has a limited number of primitive types, it stores string or numeric. A numeric value does not distinguish between Integer, Long, Double, etc. so I'm not sure why you are trying to distinguish them. Once it's stored as Json it's all considered as the same numeric type.

like image 165
bcorso Avatar answered Oct 11 '22 17:10

bcorso