JSON communication between server and client Part1

JSON (JavaScript Object Notation) provides lightweight data exchange between server and client. It is human readable.
Sending data in JSON format from server to client:
There are APIs present for many languages (Java, ASP, Flex, C, C++ etc). With the help of these APIs, we can get JSON representation for data or objects. This data can be send to client just like some other data.
On the client side browser can handle this format and one can retrieve the information send from server.
I am writing code sample for spring framework

public void getJSONInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JSONObject result = new JSONObject();
    try {
        Object obj = new Object();
        // To get JSON data from obj
       JSONObject jsonObj = JSONObject.fromObject(obj);
       result.put("result", "success");
       result.put("jsonInfo", jsonObj);
   } catch (Exception e) {
       result.put("result", "error");
  } finally {
      // Write this jsonObj in HttpServletResponse
      response.getWriter().print(result);
      response.flushBuffer();
   }
}

While on the client side, I am using jquery to make AJAX request,

function getJSONInfo() {
    $.ajax({
       url: '../location?q=getJSONInfo',
       type: "POST",
       cache: false,
       dataType: "json",
       success: function(response){
           alert(response.jsonInfo);
       },
       error: function(msg){
       }
    });
}

As we can see from the example, an ajax request is made to get JSONInfo and result is displayed in popup window.

Sending data in JSON format from client to server will be covered in part2

Comments

2 Responses to “JSON communication between server and client Part1”

  1. Vikram on August 26th, 2009 10:29 pm

    Good post!!!

  2. lempi on October 7th, 2009 5:19 pm

    Man, where is second post? Its been long time, you wrote first one.

Leave a Reply




Related Post

Changing root user password in mysql
See Servlet Spec 2.3, section 9.7.2
How to know which java version is installed in linux?
Installing mysql in linux
Connecting to mysql database
Technology