Monday, January 9, 2012

Working with JSON & PhoneGap Application

I Love to use JSON objects especially when working with PhoneGap Applications. I find it very comforting while transferring data from client to server and vice versa.

I will explain through a simple example how I use JSON to ease the client-server data transmission.

Example will be, a client asking for the details of the Employee working in the Accounts department.

Basic Algo for the Example will be as follows,
  • Client will make an Ajax request, asking for the Details of Employees working in an Accounts Department.
  • On receiving the Request, Server will fetch all the details of the Employees working in Accounts form Database, convert these details to an Json Objects and send back to the Client.
  • Client on Receiving the Response from the server will parse the JSON objects and convert the data in local JS variables and render the data at client side, i.e. in a table grid etc. as per requirements. 
At the client Side, Include the following js files,
  • json2.js 
  • jsonStringify.js
At Server Side, Include the following jar
  • json.jar
Data transferred from client (Phonegap Application) to server (Any jsp/servlet server or web service etc.) will be in the form of an Ajax request, you can make use of any JS library like Jquery, prototype, zepto etc. to make the Ajax request from client, I prefer to use Jquery or Zepto and the syntax use in the following example will be compatible with both i.e. Jquery and Zepto.

Code for the Client side Making an Ajax Request will be as follows, 

function getEmpDetails() {
type : 'POST',  
url : <Server URL>,
data : {   
   'DepartmentType': 'Accounts'
success : function(data) {       
error : function(xhr, type) { 

Explanation of the Above code, 

The function, getEmpDetails() will make an Ajax request, following are the parameters,
  • type - 'POST', here GET and POST are the two values, I prefer to make POST request.
  • url – this value indicates the server url,  Server could be the Java Servlet, jsp, Web Service etc. 
  • data – this value indicates the request parameters to be sent to the server, here in this example, the name of the department we are sending i.e. 'Accounts'.
  • datatype – this value indicates the data type of the data which will be returned form the server, here the value 'json' indicates that the data sent as the response from the server to client will be in the json format.
  • success – this function will be executed after successfully getting the response from the server, explained in detail in the later section of this example.
  • error – this function will be executed if there is some kind of error in getting the response from the server, this error type may include, some connection error to server, if the data is corrupted or not in the particular format as expected etc.
At the Server Side, 
On Receiving the Request, following snippet of the code shows the server side processing,  Here my Server is the simple Java Servlet, Dont forget to include the json.jar for the same.
I have included the comments in each and every line of the code as an explanation.

// Declare the Response Object type which will be json, as client expects response in json format.
JSONObject responseObj = new JSONObject();
//Declare a List of type JSONObject as our data will have multiple employee details working in the Accounts department,

List<JSONObject> employeeDetails = new LinkedList<JSONObject>();

//Reading the Request Parameters, 

String depeartmentType = request.getParameter(“DepartmentType”);

For getting the Employee details, server may need to query the Database, and populate the jsonobjects as follows,


// Directly moving to executing a sample query not including the //connection statements here

ResultSet rs = statement.executeQuery(“select * from employee where department = '”+depeartmentType+”'”);

while ({
// here is where the json object is populated as follows,
JSONObject empObj = new JSONObject();
empObj.put("empId", rs.getString(“ID”));      
empObj.put("empName", rs.getString(“NAME”));         
empObj.put("empDateOfJoining", rs.getString(“DOJ”));  
empObj.put("empSalary", rs.getString(“SALARY”));     
// this temp json object added to the employeeDetails List of type //JSONObject.

// finally add the populated linked list to the response object
responseObj.put("employeeDetails", employeeDetails);

// Get the print writer object and send the above response object //to the Client.
            PrintWriter writer = response.getWriter();

}catch(Exception e){

Now On Receiving the Response from the Server, the above method of the Client Side will Change as follows,

function getEmpDetails() {
  type : 'POST',  
  url : <Server URL>,
  data : {   
'Department': 'Accounts'
          success : function(data) { 
          var empObject = eval('(' + JSON.stringify(data) + ')');            
          var empObjectLen = empObject.employeeDetails.length;
          for (var i=0; i<empObjectLen; i++) {     
// Get the data in local JS variables
       var empId = empObject.employeeDetails[i].empId;
       var empName = empObject.employeeDetails[i].empName;
       var empDateOfJoining = empObject.employeeDetails[i].empDateOfJoining ;
       var empSalary = empObject.employeeDetails[i].empSalary;
     error : function(xhr, type) { 
alert('Internal Error Occoured!'); 

On successfully getting the response from the server,   Response type will be as follows,

{"empId":"005","empName":"Sam S","empDateOfJoining":"2011-04-08","empSalary":"20000"},
{"empId":"006","empName":"Pam P","empDateOfJoining":"2010-09-07","empSalary":"40000"},

Appropriate parsing of this response is done in the 'success' function, where whole response is breaked up and finally made available in the local JS variables which can be used further to render the data at client side in the Grid, tables etc. as per user requirements.

I hope this article was useful to the readers.

That's all from My End for Now!

Happy Coding!! :-))


Best Car pool Android Application Best Car Pool Application Source Code Download Here

Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here

Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here

Best Android Application Android Chat Source code download Android Chat Source code download

Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here