Search This Blog

Saturday, July 30, 2011

GWT - communicating with PHP via JSON

  Finally something useful :) I'll show you my implementations of JSON communication. Of course it took some time before I found out how to do everything myself.
  Note that this works only if your application is on the same domain and port with the server you are talking with. See my previous post http://coders-tutorials.blogspot.com/2011/07/thinking-ahead-gwt-server-side-java-or.html . Otherwise you have to use JSONP.

  Creating POST parameters
  When you want to post parameters, a String according to standard has to be created. I implemented a class that does it for me:
 
public class PostParameters {
 public String parameters = "";  //String with all parameters

 public PostParameters() { 
 }

 public void addParameter(String name, String value){
   parameters+=URL.encode(name);
   parameters+="=";
   parameters+=URL.encode(value);
   parameters+="&";
 }
}

 

All parameters have to be URL encoded. Usage can be seen in Making request topic.

  Making request

public void login(){    
  PostParameters params = new PostParameters();  //the class containing post parameters
  params.addParameter("name", nameTxtBox.getText());
  RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "php/login.php");
  builder.setHeader("Content-Type","application/x-www-form-urlencoded");
  builder.setTimeoutMillis(20000);
     try {
       Request request = builder.sendRequest(params.parameters, new RequestCallback() {
         public void onError(Request request, Throwable exception) {
          Window.alert(exception.getMessage());
         }        
         public void onResponseReceived(Request request, Response response) {
           if (200 == response.getStatusCode()) {
            handleLogin(response.getText());  //this function is called when everything ok
           } else {
            Window.alert(response.getStatusText());
           }
         }
       });     
     } catch (RequestException e) {
      Window.alert(e.getMessage());
     }    
}
In handleLogin() function is response parsing process, which is explained further.

  My JSON syntax

  All my responses have text "results:"...you can do without it...I don't know why I started using it, but that's how my server does :)
  For simple info you can send something like this (this comes from server):
  {'results': {'successfulLogin': 'true'}}
Or something like this:


{
"results": {
        "receivedSentData": [
            {
                "uuid": "10f6a663-2840-41b9-b726-91359ec7cf95",
                "regNr": "11-XXX",
                "regDate": "2011-07-11",
                "correspondent": "Mr John",
                "howReceieved": "e-document"
            },
            
        ],
        "files": [
            
        ],
        "folders": [
            {
                "author": "okmAdmin",
                "created": "2011-07-29T08:53:42.845+03:00",
                "hasChilds": false,
                "path": "\/okm:root\/LIETVDS_VDC\/2011\/IEN\/11-XXX",
                "permissions": 15,
                "subscribed": false,
                "uuid": "10f6a663-2840-41b9-b726-91359ec7cf95"
            },
            
        ],
        "totalRows": 1,
        "startRow": 0,
        "endRow": 1
    }
}



This is an example of data which I receive when populating a table. In receivedSentData I have info from database, in files and folders I have info about documents from document system. Doesn't matter...now I'll show how to parse them in GWT.


How it works
GWT has some great classes for JSON parsing, but firstly you have to use JavaScript's native function eval() which just executes received JSON data and that way you can get data object.
Personally I created a static class which parses all server responses.
public class MyParser {
 public static native JavaScriptObject parseJson(String responseString) /*-{
   return eval('('+responseString+')');
 }-*/;
}

And then it's very easy to use this parser for every response:
JSONObject json = new JSONObject(MyParser.parseJson(responseString)) \\;

Now JSONObject has the received data and can be easily parsed out. For example this is how I get all the "results" data.
JSONObject ary = json.get("results").isObject(); 

Then I can get receivedSentData array or any other object with just providing keyword:
JSONArray dataArray = ary.get("receivedSentData").isArray();

And then from array:
dataArray.get(i).isObject().get("regNr").isString().stringValue();

You can add all this parsing code in try catch blocks, so when server responds with an invalid JSON that can't be parsed, an exception occurs and you can show it.

5 comments:

  1. give this one in ppt format and give a clear picture

    ReplyDelete
  2. Use autobeans instead of javascriptobject and overlays

    ReplyDelete
  3. hmm, nice implementation of "AddParameter" method.. will use in future) thank you. Write more!

    ReplyDelete
    Replies
    1. I guess I'll do that some time later. Now I am overwhelmed with things to do - work and finishing Masters diploma. Now I am more in to Qt :) But if there is going to be any project for web application - GWT is the tool for that :)

      Delete
    2. русский понимаешь?) как я понял ты с Латвии.Чуток переделал твой меотд аддПараметер. заюзал safeHtmlBuilder вместо строки и сделал метод getParameter()
      А кьют это хорошо)

      Delete