Search code examples
gwtserializationhashmapnullpointerexceptionautobean

NullPointerException when using GWT's AutoBean deserialization with HashMap


I have some problem with the Google's AutoBean serialization and deserialization. I have an AutoBean that contains primitive types and Maps as well. I can serialize and deserialize the primitive types without any problem, but when i try to read the deserialized Map, i get NullPointerException. Have you ever met with a similar problem before? There is a JUnit test that representes my problem. The first two asserts are passes, but the third fails.

public class AutoBeanTest {

    @Test
    public void test() throws Exception {
        MyFactory myFactory = AutoBeanFactorySource.create(MyFactory.class);

        Options options = myFactory.options().as();
        options.setMyInt(5);
        HashMap<Double, Boolean> map = newHashMap();
        map.put(8.0, true);
        map.put(9.1, false);

        options.setMyMap(map);

        Options deserialized = AutoBeanCodex.decode(myFactory, Options.class, AutoBeanCodex.encode(AutoBeanUtils.getAutoBean(options)).getPayload()).as();
        assertEquals(deserialized.getMyInt(),5);
        assertTrue(options.getMyMap().containsKey(8d));
        assertTrue(deserialized.getMyMap().containsKey(8d));
    }

    public interface MyFactory extends AutoBeanFactory {
        AutoBean<Options> options();
    }

    public interface Options {

        public int getMyInt();

        void setMyInt(int myInt);

        Map<Double, Boolean> getMyMap();

        void setMyMap(Map<Double, Boolean> myMap);
    }
}

Solution

  • I've been playing around with the AutoBean functionality a while ago. I think it is still kind a buggy. I'm quite sure the exceptions is caused by a bug in the AutoBean code, not in your code.

    If you run the above sample code in a debugger and check the generated JSON, things look fine. You can even call deserialized.getMyMap().size() and get the correct value, but once you want to access the content errors occur.

    There is a workaround, just use Map<String, String> instead of Double or Boolean and it works...