在 Gson 双序列化中关闭科学记数法 [英] switch off scientific notation in Gson double serialization

查看:41
本文介绍了在 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-60.000009166666

The above will render (say) 9.166666E-6 as 0.000009166666

这篇关于在 Gson 双序列化中关闭科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆