using Gson library in GWT client code
Question
I'm currently writing a web application in java using GWT 2.0 in eclipse. I wanted to know if there is a way to use Gson library in a GWT application's client code.
and if there is a way - please tell me how...
Thanks!
Solution
Not exactly what you wrote but I guess that what you meant was how to serialize/deserialize JSON in GWT code?
In GWT 2.1.1 you can use GWT AutoBean framework
See there at the bottom of the article it has this magic code ...
String serializeToJson(Person person)
{
// Retrieve the AutoBean controller
AutoBean<Person> bean = AutoBeanUtils.getAutoBean(person);
return AutoBeanCodex.encode(bean).getPayload();
}
Person deserializeFromJson(String json)
{
AutoBean<Person> bean = AutoBeanCodex.decode(myFactory, Person.class, json);
return bean.as();
}
the serializeToJson() woks fine for me even with instances that are inherit Person but I did not try the deserializeFromJson...
OTHER TIPS
Gson uses Java features that are not supported in GWT such as reflection. Thus it is not possible to use Gson in GWT client side code.
(feel free to enhance my post if you like)
currently (2015-02-07) it is not possible although I like Gson very much and would like to have only one solution for shared code :-/ , but there are some other libraries available (I only know AutoBeans and Gson myself and had a quick look at Piriti):
(some support both or only one of XML and JSON (de)serialization)
- client- and server-side
- AutoBeans (*): http://code.google.com/p/google-web-toolkit/wiki/AutoBean
- I had problems with generics there (2015-02-07) similar to this: RequestFactory: Proxy implementing interface with generics
- AutoBeans (*): http://code.google.com/p/google-web-toolkit/wiki/AutoBean
- client-side-only
- Piriti
- RestyGWT: http://restygwt.fusesource.org/documentation/restygwt-user-guide.html#JSON_Encoder_Decoders
- RocketGWT: http://code.google.com/p/rocket-gwt/wiki/JsonSerialization
- Acris: http://code.google.com/p/acris/wiki/GWTJsonizer
- JavaScript overlay types (*)
- server-side only
- Gson (from Google)
(*) from GWT project itself
Comparisons:
In our GWT project we use piriti: http://code.google.com/p/piriti/
Works like a charm :-)
I have write a library that allows using GWT with Gson, you can download here and enjoy it.