在Gson双序列化中关闭科学记数法 [英] switch off scientific notation in Gson double serialization
问题描述
当我使用Gson序列化包含接近零的double值的Object时,它使用的是科学的E-notation:
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生成
{"doublevaule":0.00056}
相反?我可以实现自定义JsonSerializer,但它返回一个JsonElement。我必须返回一个包含double的JsonPrimitive,它不能控制序列化的方式。
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
as 0.000009166666
The above will render (say) 9.166666E-6
as 0.000009166666
这篇关于在Gson双序列化中关闭科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!