Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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}

How do I tell Gson to generate

{"doublevaule":0.00056}

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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
732 views
Welcome To Ask or Share your Answers For Others

1 Answer

Why not provide a new serialiser for Double ? (You will likely have to rewrite your object to use Double instead of double).

Then in the serialiser you can convert to a BigDecimal, and play with the scale etc.

e.g.

    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();

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...