sinamdar2015 / google-gson

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

Adding deserializer for interfaces causes serialization to fail #479

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1.Create a deserializer for an interface class and register it
2.Serialization of the interface no longer occurs.

What is the expected output? What do you see instead?
I expected to see the class serialized like it was before the deserializer was 
registered.

What version of the product are you using? On what operating system?
Using GSON version 2.1, on Windows 7 x64, using Oracle Java (32 bit) 7 update 3

Please provide any additional information below.

Here is a small example that will illustrate the issue (written as a JUnit 
test).

    public interface HelloInterface {
        public String sayHello();
    }

    public class HelloClass implements HelloInterface{
        private String hi = "hi";

        public String sayHello(){
            return hi;
        }
    }

    public class Greeter {

        private HelloInterface saysHello;

        public void setHello(HelloInterface hello){
            saysHello = hello;
        }

    }

    public void testGsonSerialization(){
        GsonBuilder builder = new GsonBuilder();
        Greeter greeter = new Greeter();
        final String expectedCorrect = "{\"saysHello\":{\"hi\":\"hi\"}}";
        final String incorrectJson = "{\"saysHello\":{}}";
        // Should be able to serialize, but not deserialize.
        greeter.setHello(new HelloClass());
        String jsonResult = builder.create().toJson(greeter);
        assertEquals(expectedCorrect, jsonResult);
        builder.registerTypeAdapter(HelloInterface.class, new JsonDeserializer<HelloInterface>() {

            @Override
            public HelloInterface deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
                // Do stuff, it doesn't even matter here.
                return null;
            }
        });
        //Registering a deserializer causes the serialization to not work anymore.
        String secondJsonResult = builder.create().toJson(greeter);
        // This line passes.
        assertEquals(incorrectJson, secondJsonResult);
        // This line fails
        assertEquals(expectedCorrect, secondJsonResult);
    }

Original issue reported on code.google.com by mdkitz...@gmail.com on 9 Oct 2012 at 9:02