XML Tutorials

  Home arrow XML Tutorials arrow Page 3 - Handling Data for Ajax with JSON
XML TUTORIALS

Handling Data for Ajax with JSON
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2008-01-10

    Table of Contents:
  • Handling Data for Ajax with JSON
  • Running the Application on Tomcat
  • Passing Data with JSON
  • Changing the JavaScript for JSON

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    Handling Data for Ajax with JSON - Passing Data with JSON


    (Page 3 of 4 )

    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'seval()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 theeval()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 aStringBuffer 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 aStringBuffer.

    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.

    More XML Tutorials Articles
    More By O'Reilly Media

    blog comments powered by Disqus

    XML TUTORIALS ARTICLES

    - Validation with Document Type Definitions (D...
    - Creating a Well-Formed XML Document
    - Getting to Know XML
    - A Friendly Approach to XML
    - Creating RSS 2.0 Feeds
    - Using Modules in Your RSS Feed
    - RSS 2.0
    - Querying XML: Use Cases
    - Joins and Query Use with XML
    - Solving Problems by Querying XML
    - Performing Set Operations When Querying XML
    - Querying XML
    - Handling Data for Ajax with JSON
    - Handling XML Data for Ajax
    - XML and JSON for Ajax


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap