简体   繁体   English

使用GSON将Hashmap转换为JSON

[英]Convert Hashmap to JSON using GSON

I have a HashMap<String, String> , where the value strings can be either a long or double. 我有一个HashMap<String, String> ,其中值字符串可以是long或double。 For example, 123.000 can be stored as 123 (stored as long), and 123.45 as 123.45 (double). 例如, 123.000可以存储为123 (存储为长), 123.45可以存储为123.45 (双123.000 )。

Take these two hashmap values: 取这两个hashmap值:

("one", "123"); (“一”,“123”); ("two", "123.45") (“两个”,“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 } 预期:{“one”:123,“two”:123.45}

Actual: {"one": "123", "two": "123.45" } 实际:{“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. 我更喜欢使用GSON的解决方案,但也欢迎使用其他库或库。

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. 基本上,没有办法让Gson自动将你的字符串转换为数值。 If you want them to show up as numeric (ie without quotes) you need to store the appropriate datatype in the map, Double or Number . 如果希望它们显示为数字(即没有引号),则需要在地图中存储相应的数据类型, DoubleNumber

Also, Json only has a limited number of primitive types, it stores string or numeric. 此外,Json只有有限数量的基本类型,它存储字符串或数字。 A numeric value does not distinguish between Integer , Long , Double , etc. so I'm not sure why you are trying to distinguish them. 数值不区分IntegerLongDouble等。所以我不确定你为什么要试图区分它们。 Once it's stored as Json it's all considered as the same numeric type. 一旦它被存储为Json,它们都被认为是相同的数字类型。

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. 使用以下链接构建自定义Gson序列化,该序列化将数字字符串解析为适当的数字类型。 (simple if-else or switch based on decimal point). (简单的if-else或基于小数点的切换)。

Gson Custom Serialization and Deserialization Gson自定义序列化和反序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM