AiorosXu / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Can't register a Double serializer #378

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

Execute:

public class Main {

    public static void main(String[] args) throws Exception {
        Gson gson = new GsonBuilder()
            .registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src.isNaN() || src.isInfinite())
                        return new JsonPrimitive(src.toString());
                    return new JsonPrimitive(src);
                }
            })
            .create();
        System.out.println(gson.toJson(21.24));
        System.out.println(gson.toJson(Double.NaN));
        System.out.println(gson.toJson(Double.POSITIVE_INFINITY));
    }

}

What is the expected output? What do you see instead?
I see this Exception:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot register 
type adapters for class java.lang.Double
    at com.google.gson.GsonBuilder.registerTypeAdapter(GsonBuilder.java:504)
    at com.google.gson.GsonBuilder.registerTypeAdapter(GsonBuilder.java:495)
    at Main.main(Main.java:13)

What version of the product are you using? On what operating system?
Upgrading from gson-1.7.1 to 2.0 introduced the issue.

Please provide any additional information below.
Thanks.

Original issue reported on code.google.com by ajk...@gmail.com on 18 Nov 2011 at 12:09

GoogleCodeExporter commented 9 years ago
Does this work for you?
  Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().build();

This will serialize NaN and Infinity, but not as strings.

Original comment by limpbizkit on 19 Nov 2011 at 3:33

GoogleCodeExporter commented 9 years ago
Yes, it works but I prefer the previous strings.

Original comment by ajk...@gmail.com on 20 Nov 2011 at 9:39

GoogleCodeExporter commented 9 years ago
I'm sorry we broke this use case with the 2.0 upgrade.

We can't support custom type adapters here in the general case without 
sacrificing some performance on binding. We're hoping to do optimizations where 
we can avoid boxing primitives but that only works when applications don't 
provide custom type adapters for primitive types.

I'm keeping this open because with some significant effort we could probably 
get Gson to handle custom type adapters as long as it knows to test for them.

Original comment by limpbizkit on 16 Dec 2011 at 5:01

GoogleCodeExporter commented 9 years ago
Fixed in 2.3 by restoring the ability to register custom serializers for 
primitive types.

Original comment by limpbizkit on 1 Jul 2012 at 5:59