A library that allows using GWT with Gson
Download from here then add to your build path.
Download Gson then add to you WEB-INF/lib
folder.
Add this to your Module.gwt.xml
:
<inherits name="com.sangnd.gwt.gson.GwtGson" />
Add this to your web.xml
:
<servlet>
<servlet-name>GwtGsonService</servlet-name>
<servlet-class>com.sangnd.gwt.gson.server.GwtGsonServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GwtGsonService</servlet-name>
<url-pattern>/YourProjectPath/gwtGsonService</url-pattern>
</servlet-mapping>
Your object class must be implemented IsSerializable
interface like this example.
Create GwtGsonServiceAsync
instance:
GwtGsonServiceAsync gwtGsonService = GWT.create(GwtGsonService.class);
Example:
gwtGsonService.toJson(new Car("Ferari", "Red", 11111), new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(String result) {
System.out.println("Result is: " + result);
}
});
Output:
Result is: {"name":"Ferari","color":"Red","value":11111}
Assume that json
is a String with value: {"name":"Ferari","color":"Red","value":11111}
Example:
gwtGsonService.fromJson(json, new Car(), new AsyncCallback<IsSerializable>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(IsSerializable result) {
if (result != null && result instanceof Car) {
Car u = (Car) result;
System.out.println("Car's name is: " + u.getName());
} else {
System.out.println("null");
}
}
});
Output:
Car's name is: Ferari
As you see, we must send a "empty" instance of Car
to send object type via RPC. If you know the more effective way to do this, send me a pull request.
Copyright (c) 2013 heroandtn3.
Licensed under the GNU General Public License. See COPYING for details.