所以我有一个动态数据,它是一个双,我试图将它添加到HashMap中,并使用Gson将其转换为Json。有时数据可以是0.00或0.0,然后我只想向HashMap添加0。为此,我使用DecimalFormat来按我的需要格式化数据(正如我前面提到的),但当我这样做时,它是将值作为JSON中的字符串。当我试图打印它时,它是作为一个数字打印出来的,但是当我将它添加到hashmap并将其转换为JSON时,它是一个字符串。我不知道我做错了什么,有人能帮我吗。这是密码。
HashMap<String, Object> field = new LinkedHashMap<>();
double heading = 0.00;
DecimalFormat decimalFormat = new DecimalFormat("##.##");
field.put("data", decimalFormat.format(heading));
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().disableHtmlEscaping().create(); // create a GsonBuilder to convert the hashmap to a Json String.
String jsonOutput = gson.toJson(field);
System.out.println( jsonOutput );假设字段哈希映射是一个大数据集,那么输出是
field{
data: "0"
}但我希望它是
field{
data: 0
}我不希望0出现在“"中。除了DecimalFormat,还有其他替代方法吗?或者有一种方法使hashmap将其作为一个数字。
发布于 2018-05-08 11:29:05
你可以直接加双倍的。葛森知道如何输出。
field.put("data", heading)有时数据可以是0.00或0.0,然后我只想向HashMap添加0。
我建议0.00、0.0和0都是相同的数字,您不应该关心哪一个在最终的JSON中结束。任何JSON解析器都能够正确地读取它。
如果您将JSON解析器(和使用者)写成字符串,那么它将被抛出。
发布于 2018-05-08 12:09:35
如果你不想要十进制后的数字。然后您可以尝试下面的代码:
field.put("data", (long) heading);发布于 2018-05-08 11:33:55
在这里,Decimalformat将输出格式化为string。检查format()的输出类型。
可以将输出解析为整数,如
field.put("data", Double.parseDouble( decimalFormat.format(heading)));https://stackoverflow.com/questions/50232492
复制相似问题