jens
jens

Reputation: 17555

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

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

Upvotes: 9

Views: 14084

Answers (4)

Dor
Dor

Reputation: 96

You have also another solution which is 3rd party solution, maybe a second place solution but it can be also the first place. The 3rd party called GSON and it's a project open source on google code. You can find it here.

I used it and it's very good and very simple.

Upvotes: 0

Hiram Chirino
Hiram Chirino

Reputation: 4091

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

Upvotes: 7

Riley Lark
Riley Lark

Reputation: 20890

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.

Upvotes: 10

BobV
BobV

Reputation: 4173

Take a look at GWT's AutoBean framework, which can be used to create and receive JSON payloads. The RequestBuilder type can be used to send HTTP requests to the server.

Upvotes: 0

Related Questions