Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT (Client) = How to convert Object to JSON and send to Server?

Tags:

java

gwt

I know that GWT has a good RPC support. But for various purposes I need to build this on my own:

1.) How can I convert a Bean Object (on the Client Side) like;

class MyPerson {

String name;
String getName();
void setName(String name);
//..    
}

with GWT into a JSON String? (Ideally only using libraries that come officially from GWT/Google).

2.) Secondly, how can I send this generated JSON String from the Client side to any Server also using any GWT Client Logik. (Ideally only using libraries that come officially from GWT/Google).

I have searched a lot, but the examples never show how to send data but only to receive JSON data.

Thank you very much!!! Jens

like image 826
jens Avatar asked Apr 14 '11 05:04

jens


2 Answers

There's a nifty class called AutoBeanFactory that GWT will create for you, no third-party libs required. See http://google-web-toolkit.googlecode.com/svn-history/r9219/javadoc/2.1/com/google/gwt/editor/client/AutoBeanFactory.html

Once you have your AutoBeanFactory, you can use it like this:

producing JSON from an object of type SimpleInterface

AutoBean<SimpleInterface> bean = beanFactory.create(SimpleInterface.class, simpleInterfaceInstance);
String requestData = AutoBeanCodex.encode(bean).getPayload();

useRequestBuilderToSendRequestWhereverYouWant(requestData);

parsing JSON from an object of type SimpleInterface

SimpleInterface simpleInterfaceInstance = AutoBeanCodex.decode(beanFactory, SimpleInterface.class, responseText).as();

You can use RequestBuilder to send these requests without GWT-RPC or the RF stuff.

like image 147
Riley Lark Avatar answered Sep 23 '22 03:09

Riley Lark


I recommend you use RestyGWT it makes JSON rest services work just like GWT RPC services.

like image 28
Hiram Chirino Avatar answered Sep 24 '22 03:09

Hiram Chirino