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

Technology