darrenmeehan / google-gson

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

Deserialization of parameterized types throws an IllegalArgumentException #576

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
The following simple test case throws an IllegalArgumentException

    public static class TestMetadata<R extends TestResource>
    {
        private R resource;
    }

    public static class TestResource
    {
        private int id;
    }

    @Test
    public void testNarrowing()
    {
        TestMetadata metadata = new com.google.gson.GsonBuilder().create().fromJson("{ 'resource':{ 'id':17 }}", new TestMetadata<TestResource>().getClass());

        Assert.assertEquals("id", 17, metadata.resource.id);
    }

I get the following exception: java.lang.IllegalArgumentException: Can not set 
com.ancestry.academy.test.unit.gson.GsonVanillaTest$TestResource field 
com.ancestry.academy.test.unit.gson.GsonVanillaTest$TestMetadata.

Version 2.2.4 on Mac OSX

Original issue reported on code.google.com by robertwi...@gmail.com on 28 Apr 2014 at 10:37

GoogleCodeExporter commented 9 years ago
You need to use a TypeToken as per 
https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deseriali
zing-Generic-Types.

Code below: 

    public static class TestMetadata<R extends TestResource>
    {
        private R resource;
    }

    public static class TestResource
    {
        private int id;
    }

    @Test
    public void testNarrowing()
    {
        TestMetadata metadata = new com.google.gson.GsonBuilder().create().fromJson("{ 'resource':{ 'id':17 }}", new TypeToken<TestMetadata<TestResource>>(){}.getType());

        Assert.assertEquals("id", 17, metadata.resource.id);
    }

Original comment by Tobias1...@gmail.com on 17 Jun 2014 at 9:53