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() {
$.ajax({       
type : 'POST',  
url : <Server URL>,
data : {   
   'DepartmentType': 'Accounts'
},  
dataType:'json',
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,

try{

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

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

while (rs.next()){
// 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.
employeeDetails.add(empObj);


// 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();
            writer.write(responseObj.toString());
            writer.flush();


}catch(Exception e){
e.printStackTrace();
}



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

function getEmpDetails() {
$.ajax({       
  type : 'POST',  
  url : <Server URL>,
  data : {   
'Department': 'Accounts'
       },  
  dataType:'json',   
          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!'); 
}  
}); 
}

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

{"employeeDetails":[{"empId":"001","empName":"Sam","empDateOfJoining":"2011-07-07","empSalary":"60000"},
{"empId":"002","empName":"Pam","empDateOfJoining":"2010-06-07","empSalary":"40000"},
{"empId":"003","empName":"Dolly","empDateOfJoining":"2010-07-09","empSalary":"80000"},
{"empId":"004","empName":"Dona","empDateOfJoining":"2010-07-07","empSalary":"40000"},
{"empId":"005","empName":"Sam S","empDateOfJoining":"2011-04-08","empSalary":"20000"},
{"empId":"006","empName":"Pam P","empDateOfJoining":"2010-09-07","empSalary":"40000"},
{"empId":"007","empName":"Polla","empDateOfJoining":"2012-01-01","empSalary":"70000"}]}


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!! :-))

~Mayuri





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



19 comments:

Kiddo said...

Thks goog sample

Aamirkhan.I said...

very use full code thanks for poasting i learn a lot.

please see my blog tech-droidaamir.blogspot.in

Aamirkhan.I said...

very use full post thanks,,i learn a lot
please see my blog
tech-droidaamir.blogspot.com

Aamirkhan.I said...

very use full code thanks for poasting i learn a lot.

please see my blog tech-droidaamir.blogspot.in

Nandakishore Shetty said...

Good ONE :-) Do you have any idea how data can be sync from device to server Using JSON? Example in my phonegap Android App, I have employees details which is stored on Sqlite which i want to sync to my remote database like MS Sql server.

Any IDEA!!!?

Nandakishore Shetty said...

Good ONE :-) Do you have any idea how data can be sync from device to server Using JSON? Example in my phonegap Android App, I have employees details which is stored on Sqlite which i want to sync to my remote database like MS Sql server.

Any IDEA!!!?

Nandakishore Shetty said...

Good ONE :-) Do you have any idea how data can be sync from device to server Using JSON? Example in my phonegap Android App, I have employees details which is stored on Sqlite which i want to sync to my remote database like MS Sql server.

Any IDEA!!!?

Tizbn said...

Dear Mayuri and all ,

I have developed json file in server and able to read the data . Now my question is how can I sync the data between server and mobile when there is any changes in json file.

hope you all will be response soon.

jagadesh said...
This comment has been removed by the author.
jagadesh said...

Thank u for the good infromation

I do have one more requirement, you have explained how to generate the json object, i want to parse the json object based on the element.

andy said...

very good, thank you

akhtar miah said...

Hi there, im trying to get my head around jquery and server communications. how do you declare DepartmentType in your example. is it passed down from a form in the client side?

could you post the example online?

many thanks

akhtar miah said...

Hi there, im trying to get my head around jquery and server communications. how do you declare DepartmentType in your example. is it passed down from a form in the client side?

could you post the example online?

many thanks

Manivel said...

hi i am using php as server side in phonegap.. can you tell me where to add json.jar file in php??

Manivel said...

hi i am using php as my server side in phonegap application.. can you tell me how to add json.jar file in php??

C Prithivi said...

hi i would to like to learn lot about phonegap will u help one small quiz application in phonegap with prev next button and show summary results

R.Eder Weiss J. said...

Awesome!! Thanks!!

jigar patel said...

Useful to a coder in Surat :-)

andy ansy said...

hello pls review my question.

http://stackoverflow.com/questions/28338435/ajax-post-returning-status403-statustextforbidden-cordova-android