Tuesday, 11 September 2012

GWT RPC: The response could not be deserialized only when using Lists

"The response could not be deserialized" is one of the very basic error you may come up with when using GWT-RPC. The reason is usually quite simple but sometimes could be more cryptic.

com.google.gwt.user.client.rpc.SerializationException: The response could not be deserialized, com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException: The response could not be deserialized 

If you google the errors above, you will end up finding answers to most common mistakes done when using GWT-RPC.

The most common error is failing to implement IsSerializable or Serializable interfaces. You may feel like using java both on the server and the client but GWT needs to translate every Java object to its Javascript counterpart. To achieve that when using rpc calls, all objects exposed to this call should be serialized which can only happen if the object has implemented on of those two interfaces. When GWT first came out, it offered its own version of serialization interface, IsSerializable. However, later the the convention was moved to default java Serializable interface. So using either is fine but current convention is using the Serializable interface. Keep in mind all nested objects needs to implement Serializable, not only the root object.

The second common error is the missing default constructor. GWT needs to instantiate your objects using the default constructor which is created by the default by the compiler if you did not add any non default constructor. So if you had add constructor(s) with parameter(s), never ever forget to add an empty default constructor.

Third and most challenging problem is a bit more cryptic because actually the serialization works when the service returns the objects you created, however, only fail when returning a list or arraylist of those objects. The first two solutions does not apply for sure since the object can be serialized when returned directly. The reason of this error is using the wrong version of gwt-servlet.jar in project class path. Google plugin adds this jar when a GWT project is created. However if you convert the project to maven and add get as a maven dependency or manually add any GWT library, you may end up with 2 gwt-servlet.jars in your classpath.

Check the buildpath, dependencies, deployment descriptor, maven dependencies and WEB-INF/lib folder (this is where gwt adds the servlet jar) for any duplicates or any other version then the gwt compiler you are currently using.