java 使用 GSON 将 Hashmap 转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31620675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Hashmap to JSON using GSON
提问by user3366706
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).
我有一个HashMap<String, String>
,其中的值字符串可以是 long 或 double。例如,123.000
可以存储为123
(stored as long),和123.45
为123.45
(double)。
Take these two hashmap values:
取这两个 hashmap 值:
("one", "123"); ("two", "123.45")
(“一”,“123”);(“二”、“123.45”)
When I convert the above map into a JSON string, the JSON values should not have double quotes, like
当我将上面的映射转换为 JSON 字符串时,JSON 值不应包含双引号,例如
Expected: {"one": 123, "two": 123.45 }
Actual: {"one": "123", "two": "123.45" }
预期:{“一”:123,“二”:123.45 }
实际:{“一”:“123”,“二”:“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.
我更喜欢使用 GSON 的解决方案,但也欢迎使用其他库。
回答by bcorso
For Gson you'll get the following conversions:
对于 Gson,您将获得以下转换:
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
.
基本上,没有办法让 Gson 自动将您的字符串转换为数值。如果您希望它们显示为数字(即没有引号),您需要在地图中存储适当的数据类型,Double
或者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.
此外,Json 只有有限数量的原始类型,它存储字符串或数字。一个数值不区分Integer
,Long
,Double
,等。所以我不知道为什么你想区分它们。一旦它被存储为 Json,它就被认为是相同的数字类型。
回答by Adi
This is very late to answer this but it will help someone who stumble upon this issue like me.
回答这个问题为时已晚,但它会帮助像我这样偶然发现这个问题的人。
Use following link to build your custom Gson serialization which will parse the numeric string to appropriate number type. (simple if-else or switch based on decimal point).
使用以下链接构建您的自定义 Gson 序列化,它将数字字符串解析为适当的数字类型。(简单的 if-else 或基于小数点的切换)。