Search code examples
javagwtrestlet

JSON to POJO and vise-versa for GWT


My applications use common Models integrated as dependencies for multiple application. One of the app the has a dependency on the Models have a Restlet connection through Restlet:

ClientResource res = new ClientResource("/path");
            res.setOnResponse(new Uniform() {
                @Override
                public void handle(Request request, Response response) {
                    try {
                        if(!response.getStatus().isError()){
                           String body = response.getEntity().getText();
                          // do stuff with Response JSON
                        } else {

                        }
                    } catch (IOException e) {
                       // handle error
                    }
                }
            });
res.post(new JsonRepresentation(MediaType.APPLICATION_JSON, jsonObject));

I have two questions for this,

  1. Is there a straightforward way for marshalling a POJO into a com.google.gwt.json.client.JSONObject in GWT for use with the res.post above
  2. Is there a straightforward way for marshalling a JSON String into a POJO with GWT?

That is both applicable in the ClientResource above as well as not resort into using GWT Overlay types as we already a Model shared in both client and server-side. Something that is straightforward.


Solution

  • The bean / JSON conversion isn't supported by Restlet out of the box. If you want to use beans within Restlet, you should use the native GWT protocol. It's the guidance that chose Restlet for its GWT implementation. You could have the content types enabled within Restlet and select the one you want with the content negotiation (GWT RPC for GWT clients and JSON for others).

    That said, I understand your approach. Restlet leverages the generator feature to directly work on beans in the case of the GWT RPC (see this class https://github.com/restlet/restlet-framework-java/blob/master/modules/org.restlet/src/org/restlet/rebind/ClientProxyGenerator.java.gwt). The generator only support the media type for GWT RPC but could be extended to handle other media types like JSON. Notice that such approach is tricker that the one provided by Ümit in its answer.

    Hope it give you some hints to fix your problem, Thierry