JamesDeCarlo / google-gson

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

Serialization of generic collections is broken #351

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
class Test {
    static class Dummy1 {
        List<String> str = Arrays.asList("Test");
    }

    static class Dummy2 {
        List str = Arrays.asList("Test");
    }

    static class Dummy3<T> {
        List<T> str;

        public Dummy3(List<T> str) {
            super();
            this.str = str;
        }
    }

    public static void main(String[] args) {
        System.out.println(new Gson().toJson(new Dummy1()));
        System.out.println(new Gson().toJson(new Dummy2()));
        System.out
                .println(new Gson().toJson(new Dummy3(Arrays.asList("Test"))));
    }   
}

Expected output:
{"str":["Test"]}
{"str":["Test"]}
{"str":["Test"]}

Got:
{"str":["Test"]}
{"str":["Test"]}
{"str":[{}]}

I find it really awkward

I figured out the reason is that `CollectionTypeAdapter` resolves 
`childGenericType` to `T`. It would be perfect if it simply serialized 
collections as if they were not generic at all.

Original issue reported on code.google.com by konrad.g...@gmail.com on 1 Aug 2011 at 4:05

GoogleCodeExporter commented 9 years ago
You need to use the two-arg form of Gson.toJson():
  new Gson().toJson(o, new TypeToken<<Dummy3<String>>() {});
Otherwise GSON doesn't have the type information that it needs to do a good job.

Original comment by limpbizkit on 2 Aug 2011 at 6:22