Deserializing/serializing JSON with GWT

A fairly typical use case: a GWT server-side component serializes java objects into Json, to be consumed by GWT clients.

Server-side serialization is actually very easy thanks to the google-gson library. It's literally a one-liner:
String json =new Gson().toJson(myObject);

On the client side things are a little bit more complicated. Gson (or any other library with features which are not supported on a GWT client such as reflection, dynamic class-loading, multithreading... ) cannot be used.

One possible alternative is to use autobeans

To deserialize a Person class
class Person {
   private String name;
   public String getName();
   public void setName(String s);
}

1. define an interface for the class to deserialize
interface IPerson {
   public String getName();
   public void setName(String s);
]

2. Mark the class to deserialize as implementing the above interface
class Person implements IPerson {...}

3. Define the interface extending AutoBeanFactory
interface Beanery extends AutoBeanFactory{  
   AutoBean <IPerson> createBean();
}

4. Instantiate the bean factory and deserialize
 
Beanery beanFactory = GWT.create(Beanery.class);
IPerson person = AutoBeanCodex.decode(beanFactory, IPerson.class, json).as();


3 comments:

  1. I have write a library that allows using GWT with Gson, you can download here and enjoy it: https://github.com/heroandtn3/bGwtGson

    ReplyDelete
    Replies
    1. Yo know, that you send the object back to server using GWT-RPC, just to create a JSON string? The standard use case of JSON in GWT client code is for serverinteraction. So you make a call to the GWT ServerCode to create a string, which you will send to sevrer again.

      Delete