Search code examples
javajsongwtjson-rpcresty-gwt

Encoding A Java Object (POJO) into a JSON String in GWT


Objective

I'd like to use JSON-RPC to send this on the clientside:

{"jsonrpc":"2.0","method":"RegisterValues","params":[["Planets","Stars"]],"id":2}

My Attempt

Using Resty-GWT:

public interface testService extends RestService {

    @Produces("application/json")
    @POST
    public void myCall(Params myparams, MethodCallback<Response> callback );

    public class Params {
          String jsonrpc = "2.0";
          String method;
          //String[] params;
          Map<String, String> params;
          int id;

          public void setId(int id){
              this.id = id;
          }

          public void setMethod(String method){
              this.method = method;
          }
                          }

          public void setParams(Map<String, String> params){
              this.params = params;
          }

        }

When I call upon the Params object in another class (to set up the call), doing something like this:

Map<Integer, String> myParams = new HashMap<Integer, String>(); 
myParams.put(0, "Planets");
myParams.setParams(myParams);

Obviously this then sends it like:

{"jsonrpc":"2.0", "method":"RegisterValues", "params":{"0":"Planets"}, "id":0}

I can't figure out how to get those magic: [["Planets"]]

I tried using a String[] but this gives me the result: ["Planets"]

String[][] gives the error that it isn't supported yet.

Horrible Hack

If I pass a String in my testService as:

String myparams = "{\"jsonrpc\":\"2.0\",\"method\":\"RegisterValues\",\"params\":[[\"FPlanets\"]],\"id\":2}";

It works but obviously this is horrible.

I tried using GSON to encode the POJO, but GWT doesn't allow reflections. I tried using thetransactioncompany to parse the object into a 'String' but couldn't figure out the <inherits> I needed in my gwt.xml file.

Any thoughts?


Solution

  • Try this one

    List<List<String>> params;
    

    instead of

    Map<String, String> params;
    

    in your Params POJO class.

    Read my post here about How to create a POJO class structure from an JSON string.


    below JSON string

    "params":[["Planets","Stars"]]
    

    represents a List<List<String>> where "params" is a variable name in your POJO.

    POJO:

    class Params implements Serializable {
        private String jsonrpc;
        private String method;
        private int id;
        private List<List<String>> params;
        ...
       //getter/setter
       //default constructor
    }
    

    Try this one at server side

    String myparams = "{\"jsonrpc\":\"2.0\",\"method\":\"RegisterValues\",\"params\":[[\"FPlanets\"]],\"id\":2}";
    Params params=gson.fromJson(myparams,Params.class);
    System.out.println(params.params+"-"+params.id);
    

    Send the Params object back to client.