GWT : JSON Parsing in client side and server side

2019-07-10 13:06发布

问题:

We use org.json api to parse json on server side and GWT JsonParser to parse JSON on client side. Is there a api that we can use that can be used on both the client side and server side?

回答1:

You are looking for GWT AutoBean: http://code.google.com/p/google-web-toolkit/wiki/AutoBean

With AutoBeans you juset define the structure of your JSON and the GWT Compiler handles the rest.



回答2:

I am writing this in comparison to using autobeans or GWT-RCP - if you are using Java on the server. Especially so, if you are not.

The cleanest way is REST-RPC/JPA, where you can share a single set of POJOS between client, server and persistence db. Let me brag on behalf of this technology mix - one single set of POJOs, instead of three, without any (or minimal) transformation between the three fronts.

You should not have to write any data transformation routines. Or at least, only minimal amount of data transformation due to serialization constraints or because you are trying to interface GWT and REST with an existing schema which presents a high degree of non-serializability.

As well as, similar to GWT-RPC, sharing a single set of Java RPC methods on both client-server sides. Well, nearly the same set of methods. Except that the return type on the server-side becomes the callback generic parameter on the client-side.

The mix of technology is:

  • JAX-RS (either Resteasy or Jersey on the server side)
  • JAX-RS + GWT = RestyGWT on the client-side
  • JPA on the server-side
  • JAXB over JAX-RS on both GWT client and server-side.
  • Jackson JSON processor on server-side.

Compelling reasons for REST-RPC is

  • you could pretend you writing client-server conversations as GWT-RPC. The service interface and callback attitude is the same.
  • The data interchange between client and server is in JSON.
  • Which means you could use a browser instead of your GWT client to converse with the server after you have successfully set up your app. Or jQuery. Or PHP, or Python as the server.
  • no need to muck around with the JSON or XML encode/decode yourself - deal in POJO and only in POJO.
  • you could use the browser to debug your web service independent of the GWT client.

The attitude of REST is (besides state independent requests) is the concept called a Web API. An API like a javadoc, perhaps - but stated in terms of JSON or XML. The wonderful thing about this API is - you do not have to generate the documentation. Like a javadoc, you could run Enunciate over the service interface.

You could follow my discussion in the following (3+ part) blog post: http://h2g2java.blessedgeek.com/2012/07/gwt-with-jax-rs-and-jpa-part-3.html.