JSON (JavaScript Object Notation) is a light weight data interchange format alternative to using xml with Ajax. It is a subset of the JavaScript object literal notation that which is basically made of 2 object types. The first being a collection of name value pairs similar to a hash table. An ordered list of values is the other, basically representing an array. The following shows how to write a JSON object in JavaScript and access it.
var company = {
name: "Software Inc.",
employees: [
{
name: "Mike",
skill: "Java"
},
{
name: "Joe",
skill: "HTML"
},
{
name: "Betty",
skill: "C++"
}
]
};
// Access the data
var employee2 = company.employees[1];
alert(employee2.name + " is skilled with " + employee2.skill + " and works for " + company.name);
This would alert “Joe is skilled with Java and works for Software Inc.”. JSON objects can also be returned from AJAX requests to the server. This can be done with the use of the org.json API to create the object in the servlet. It contains the class JSONObject which represents the collection of name value pairs. The ordered list is implementing with the JSONArray class. Here is how the above object company would be created in a servlet and returned to the AJAX callback function.
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws java.io.IOException, ServletException
{
JSONObject company = new JSONObject();
company.put("name","Software Inc.");
JSONArray employees = new JSONArray();
JSONObject employee1 = new JSONObject();
employee1.put("name","Mike");
employee1.put("skill","Java");
employees.put(employee1);
JSONObject employee2 = new JSONObject();
employee2.put("name"," Joe");
employee2.put("skill","HTML");
employees.put(employee2);
JSONObject employee3 = new JSONObject();
employee3.put("name","Betty");
employee3.put("skill","C++");
employees.put(employee3);
company.put(employees);
res.setContentType("application/x-json");
res.getWriter().print(company.toJSONObject());
}
Once the response is received in the callback function it needs to be parsed on the client side. This can be done with the JavaScript eval() function since JSON is a subset of JavaScript this produces a valid object. The downside to this is that it will compile and execute JavaScript code that is in the response, which could cause security concerns depending on the environment. There is also a JSON parser that parses out the JSON objects without executing any code. Here is one way the above response would be parsed.
var company = eval('(' + JSONResponse + ')');
The company object can then be accessed in the same manner as the first example. So you can see it’s a pretty simple and straight forward alternative to sending back server side XML. For some resources and more information about JSON check out:
http://www.json.org
Comments
The first example should state "Joe is skilled with HTML..." :-)
Post new comment