switch off scientific notation in Gson double serialization(在 Gson 双序列化中关闭科学记数法)
问题描述
当我使用 Gson 序列化一个包含接近零的双精度值的对象时,它使用的是科学 E 符号:
When I use Gson to serialize an Object that contains a double value close to zero it is using the scientific E-notation:
{"doublevaule":5.6E-4}
如何告诉 Gson 生成
How do I tell Gson to generate
{"doublevaule":0.00056}
相反?我可以实现一个自定义的 JsonSerializer,但它返回一个 JsonElement.我将不得不返回一个 JsonPrimitive,其中包含一个无法控制其序列化方式的 double.
instead? I can implement a custom JsonSerializer, but it returns a JsonElement. I would have to return a JsonPrimitive containing a double having no control about how that is serialized.
谢谢!
推荐答案
为什么不为 Double 提供一个新的序列化器?(您可能必须重写您的对象以使用 Double 而不是 double).
Why not provide a new serialiser for Double ? (You will likely have to rewrite your object to use Double instead of double).
然后在序列化器中,您可以转换为 BigDecimal,并使用比例等.
Then in the serialiser you can convert to a BigDecimal, and play with the scale etc.
例如
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
@Override
public JsonElement serialize(final Double src, final Type typeOfSrc, final JsonSerializationContext context) {
BigDecimal value = BigDecimal.valueOf(src);
return new JsonPrimitive(value);
}
});
gson = gsonBuilder.create();
上面将呈现(比如)9.166666E-6 为 0.000009166666
The above will render (say) 9.166666E-6 as 0.000009166666
这篇关于在 Gson 双序列化中关闭科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Gson 双序列化中关闭科学记数法
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
