Thursday, June 6, 2013

AutoBean - JSON to GWT Bean

GWT AutoBean Framework


                             The AutoBean framework provides automatically-generated implementations of bean-like interfaces and a low-level serialization mechanism for those interfaces. AutoBeans can be used in both client and server code to improve code re-use. For example, the Requestfactory system uses AutoBeans extensively in both the client and server code. This document describes the state of AutoBeans as found in the GWT 2.1.1 release onward.

This is quick start up article. See official article on Auto Bean for detailed information.

https://code.google.com/p/google-web-toolkit/wiki/AutoBean

Steps to integrate AutoBean

1) Create a POJO and corresponding interface
2) Create a AutoBean factory 
3) Encode or Decode JSON

AutoBean

An AutoBean must be parameterized with an interface type (e.g. AutoBean<Person>). This interface type may have any type hierarchy and need not extend any particular type in order to be usable with AutoBeans. A distinction is made as to whether or not the target interface is "simple."
A simple interface satisfies the following properties:
  • Has only getter and setter methods
  • Any non-property methods must be implemented by a category
A simple AutoBean can be constructed by the AutoBeanFactory without providing a delegate instance.
If a reference interface is returned from a method in a target interface, that instance will be automatically wrapped by an AutoBean instance. This behavior can be disabled by placing a @NoWrap annotation on the AutoBeanFactory.

POJO which used to encode or decode

// Declare any bean-like interface with matching getters and setters, no base type is necessary
interface Person {
  Address getAddress();
  String getName();
  void setName(String name);
  void setAddress(Address a);
}
interface Address {
  String getDoorNo();
  String getStreet();
  String getCity();
  String getZipcode();
  String setDoorNo();
  String setStreet();
  String setCity();
  String setZipcode();
}


Factory holds list of data binding POJO 

interface AppAutoBeanFactory extends AutoBeanFactory {
  // Factory method for a simple AutoBean
  AutoBean<Person> person();

  // Factory method for a non-simple type or to wrap an existing instance
  AutoBean<Person> person(Person toWrap);
}

Decode JSON to POJO



AppAutoBeanFactory factory = GWT.create(AppAutoBeanFactory.class);
AutoBean<Person> autoBean = AutoBeanCodex.decode(factory, Person.class, json);

Person personPojo = autoBean.as();


Encode POJO to JSON

AppAutoBeanFactory factory = GWT.create(AppAutoBeanFactory.class);
// Construct the AutoBean
AutoBean<Person> person = factory.person();
person.setName(...);
....
AutoBeanCodex.encode(person).getPayload();





No comments:

Post a Comment