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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With