Section 4.6. Passing Data with JSON


4.6. Passing Data with JSON

Now that you've seen how to use XML as the data vehicle, we must talk about some of the problems with XML. One major drawback is speed. XML requires two tags per data point, plus extra tags for parent nodes and so on. All this extra data in transmission slows down the data exchange between the client and server. You can easily end up with a long document that contains only a few bytes' worth of data. Constructing the document can also be a rather elaborate process that requires a lot of memory on the server.

Fortunately, there is another way to send data to the client that is easier to parse and more compact. That alternative is JSON (pronounced Jason). JSON objects are typically smaller than the equivalent XML documents, and working with them is more memory-efficient.

The other great benefit of JSON is that you can parse it with JavaScript's eval( ) function. You don't need other libraries, and you don't need to worry as much about cross-browser functionality. As long as your browser has JavaScript enabled and supports the eval( ) function, you will be able to interpret the data.

You may still need to use XML (and now you know how), but if you have the option, there are compelling reasons to use JSON. In most cases, you will be better off with a JSON implementation.

This is our data object represented in JSON:

 {"conversion":{ "decimal": "120", "hexadecimal": "78", "octal": "170", "hyper": "&0x78", "binary": "1111000B"} } 

There are programmatic ways to build the JSON object, but to keep it simple we'll use a StringBuffer again and glue together the strings that will form the conversion object. Example 4-10 illustrates how we build the data object in the servlet.

Example 4-10. AjaxJSONServlet.java

 package com.oreilly.ajax.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxResponseServlet extends HttpServlet {     private static final long serialVersionUID = 1L;     public void doGet(HttpServletRequest req, HttpServletResponse res)             throws ServletException, IOException {         // key is the parameter passed in from the JavaScript         // variable named url (see index.html)         String key = req.getParameter("key");         if (key != null) {             // extract the first character from key             // as an int, then convert that int to a String             int keyInt = key.charAt(0);             // set up the response             res.setContentType("text/xml");             res.setHeader("Cache-Control", "no-cache");             // write out the XML string             String outString = createStringBufferJSON(keyInt);             res.getWriter( ).write(outString);         }         else {             // if key comes back as a null, return a question mark             res.setContentType("text/xml");             res.setHeader("Cache-Control", "no-cache");             res.getWriter( ).write("?");         }     }     public String createStringBufferJSON(int keyInt) {         StringBuffer returnJSON = new StringBuffer("\r\n{\"conversion\":{");         returnJSON.append("\r\n\"decimal\": \""+                           Integer.toString(keyInt)+"\",");         returnJSON.append("\r\n\"hexadecimal\": \""+                           Integer.toString(keyInt,16)+"\",");         returnJSON.append("\r\n\"octal\": \""+                           Integer.toString(keyInt,8)+"\",");         returnJSON.append("\r\n\"hyper\": \"&0x"+                           Integer.toString(keyInt,16)+"\",");         returnJSON.append("\r\n\"binary\": \""+                           Integer.toString(keyInt,2)+"B\"");         returnJSON.append("\r\n}}");         return returnJSON.toString( );     } } 

That wasn't all that different from creating an XML document with a StringBuffer.

An alternative approach is to use the JSON library. Download json_simple.zip from http://www.JSON.org/java/json_simple.zip, and unzip it. Copy the json_simple.jar file from the lib directory into your WEB-INF/lib directory, and then add to it the import from json_simple:

 import org.json.simple.JSONObject; 

Now the code from Example 4-10 can be written as shown in Example 4-11.

Example 4-11. Writing JSON support with the json_simple library

 public String createJSONwithJSONsimple(int keyInt) {     JSONObject obj = new JSONObject( );     JSONObject obj2 = new JSONObject( );     obj2.put("decimal",Integer.toString(keyInt));     obj2.put("hexadecimal",Integer.toString(keyInt,16));     obj2.put("octal",Integer.toString(keyInt,8));     obj2.put("hyper","&0x"+Integer.toString(keyInt,16));     obj2.put("binary",Integer.toString(keyInt,2)+"B");     obj.put("conversion",obj2);     return(obj.toString( )); } 

The first JSONObject, obj, encapsulates the second object to product the result. The JSON object built with json_simple.jar looks like this:

 {"conversion":{"decimal":"103","hyper":"&0x67","octal":"147","hexadecimal":"67", "binary":"1100111B"}} 

You can nest objects with the json_simple library. As a matter of fact, you can nest objects in a JSON array. You'll learn more about JSON arrays and JSON objects in Chapter 5.

Another JSON library, called jsontools, is located at http://developer.berlios.de/projects/jsontools/. The manual for the jsontools project does a really great job of explaining JSON and how to use the jsontools library, so you may want to download it if you're looking for a good primer on JSON.

Also, don't forget to look at the documentation at http://www.JSON.org.

4.6.1. Changing the JavaScript for JSON

Now let's look at the client JavaScript code. I've replaced two functions with one: I removed msPopulate( ) and nonMSPopulate( ), and now all browsers use the populateJSON( ) function shown in Example 4-12.

Example 4-12. The populateJSON( ) function

 function populateJSON( ) {     var jsonData = req.responseText;     var myJSONObject = eval('(' + jsonData + ')');     var decimal = document.getElementById('decimal');     decimal.value=myJSONObject.conversion.decimal;     var hexadecimal = document.getElementById('hexadecimal');     hexadecimal.value=myJSONObject.conversion.hexadecimal;     var octal = document.getElementById('octal');     octal.value=myJSONObject.conversion.octal;     var binary = document.getElementById('bin');     binary.value=myJSONObject.conversion.binary;     var hyper = document.getElementById('hyper');     hyper.value=myJSONObject.conversion.hyper; } 




Ajax on Java
Ajax on Java
ISBN: 0596101872
EAN: 2147483647
Year: 2007
Pages: 78

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net