問題描述
當(dāng)我使用 Gson 序列化一個(gè)包含接近零的雙精度值的對象時(shí),它使用的是科學(xué) 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}
相反?我可以實(shí)現(xiàn)一個(gè)自定義的 JsonSerializer,但它返回一個(gè) JsonElement.我將不得不返回一個(gè) JsonPrimitive,其中包含一個(gè)無法控制其序列化方式的 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
提供一個(gè)新的序列化器?(您可能必須重寫您的對象以使用 Double
而不是 double
).
Why not provide a new serialiser for Double
? (You will likely have to rewrite your object to use Double
instead of double
).
然后在序列化器中,您可以轉(zhuǎn)換為 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();
上面將呈現(xiàn)(比如)9.166666E-6
為 0.000009166666
The above will render (say) 9.166666E-6
as 0.000009166666
這篇關(guān)于在 Gson 雙序列化中關(guān)閉科學(xué)記數(shù)法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!