Summary
What would you rather use in an AJAX app: JSON or XML? While XML puts the X in AJAX, JSON is becoming a popular alternative to encode data between a JavaScript client and a server. Zarar Siddiqi's java.net tutorial demonstrates a common AJAX use-case with JSON and the Dojo I/O library—and without a single line of XML.
Advertisement
While AJAX stands for "asynchronous JavaScript and XML," is a browser-based rich-client app that uses scant amounts of XML, or no XML at all, still an AJAX app?
Aside from philosophical nitpicking about the definition of AJAX, this question brings to light an important issue: Some developers shy away from AJAX partly because XML is not an easy programming tool to work with. XML is often an intermediate format: You have to convert your data to XML, send the XML over the wire, and then convert the XML back to some representation suitable for the client programming language.
JSON, or JavaScript Object Notation, aims to simply that process in the context of JavaScript on the client. JSON is an alternate data interchange format between JavaScript and another language for which there is a JSON implementation—a list that includes Java, C, C++, C#, and host of other languages.
JSON's main advantage is that it provides a very simple mechanism to encode the values contained in objects or even in database records. First, JSON defines a collection of name and value pairs analogous to a record or an object's instance variables. Second, it provides a structure to represent an ordered list of values, such as those in an array or a list. JSON was designed to be used easily with JavaScript code, especially in the context of making requests from JavaScript to the server.
Zarar Siddiqi's java.net article combines JSON and Dojo's I/O package to facilitate interaction between JavaScript code in the client and an object on the server. The Dojo library is fast becoming one of the most complete JavaScript libraries for Ajax development. A collection of many Ajax-related APIs, Dojo includes a widget toolkit, a set of collections and utility classes, as well as an I/O package.
One of Zarar's examples implements a simple but common AJAX use-case:
The user is viewing a list of books. When the user's mouse hovers over a book title, we also retrieve and display all other relevant information about the book using Ajax.
On the server, the book is represented with a Book pojo with four fields, and a method for encoding the field values to a JSON String representation:
public String toJSONString() throws JSONException {
JSONObject jsonObj = new JSONObject();
jsonObj.put("bookId", new Integer(this.bookId));
jsonObj.put("title", this.title);
jsonObj.put("isbn", this.isbn);
jsonObj.put("author", this.author);
return jsonObj.toString();
}
The JSONObject class acts as a converter for the Book object into a string wrapped in curly braces, with colons between the names and values and commas between the values and names--in other words, an eval()able JavaScript string. In a similar manner as shown above, the JSONArray class can convert collections of Java objects into JavaScript arrays.
Next, the article focuses on how to transfer this String back and forth between client code and the server. The server exposes books via a JSP that consumes a book ID as a parameter, interacts with the business layer to retrieve the corresponding book, and returns the JSON-ified String encoding of the book. More interesting is the way the client's JavaScript invokes the JSP:
Each element in the list [of books in a table] has a mouseover (trMouseOver) and mouseout (trMouseOut) event handler attached to its [table-row element]. On each mouseover, we call book.jsp and pass in the bookId as a parameter. The resulting data will be the JSON String for that Book.
function trMouseOver(bookId) {
getBookInfo(bookId);
}
function trMouseOut(evt) {
var bookDiv = document.getElementById("bookInfo");
bookDiv.style.display = "none";
}
function getBookInfo(bookId) {
var params = new Array();
params['bookId'] = bookId;
var bindArgs = {
url: "book.jsp",
error: function(type, data, evt){
alert("error");
},
mimetype: "text/json",
content: params
};
var req = dojo.io.bind(bindArgs);
dojo.event.connect(req, "load", this, "populateDiv");
}
function populateDiv(type, data, evt) {
var bookDiv = document.getElementById("bookInfo");
if (!data) {
bookDiv.style.display = "none";
} else {
bookDiv.innerHTML = "ISBN: " + data.isbn +
" Author: " + data.author;
bookDiv.style.display = "";
}
}
The interesting part is how the request is bound to the Dojo I/O package in:
var req = dojo.io.bind(bindArgs);
dojo.event.connect(req, "load", this, "populateDiv");
The article illustrates that Dojo and JSON provide a potentially much more streamlined mechanism to invoke a server-side Java object from JavaScript code than would be possible with hand-coded JavaScript I/O (directly using XMLHttpRequest) and XML. And while JSON is designed as a data encoding to work with JavaScript, it seems useful as a general-purpose data transfer format even in the context of other rich-client applications, such as Swing.
Would you rather use JSON or XML for client-server interaction in an AJAX app? If JSON does simplify client-server interaction, what are the downsides of using JSON versus using XML?
Faced with this choice recently, I elected to work with neither on the server side and serve up html back on the client; but had I been forced to choice one or the other, I would go with xml.
The last thing I need is another tool to "solve" the xml "problem". To me, that's like "solving" the sql "problem". xml is a data exchange format. Develop a framework to work with it, (in java any number of tools), and it's gold. On the contrary, JSON is for primarily JS devs who aren't interested in mastery of, well, xml. It's part of the JSON mission statement...
I respectfully submit it's time to learn how to work with the data, not try to hide away.
> Faced with this choice recently, I elected to work with > neither on the server side and serve up html back on the > client; but had I been forced to choice one or the other, > I would go with xml.
That sounds like what most Web apps have been doing - creating the entire response, including all the formatting, on the server, and sending only the HTML to display to the client. Inasmuch as XHTML is also XML, you can even say that you're sending XML to the client, although you may not programmatically alter that XML in the client.
But in the context of the use-case mentioned in the article, the idea is to load a page with, say, a table of books, and only when the user moves the mouse over a table row request the additional book detail data from the server. So in that context you do have to somehow parse and manipulate the data on the client—although, I suppose, sending back readily-formatted HTML and just letting the browser display that HTML, would be an option, too.
> The last thing I need is another tool to "solve" the xml > "problem". To me, that's like "solving" the sql > "problem". xml is a data exchange format. Develop a > framework to work with it, (in java any number of tools), > and it's gold. On the contrary, JSON is for primarily JS > devs who aren't interested in mastery of, well, xml. It's > part of the JSON mission statement... >
One problem with XML is that it forces a hierarchical view of data, even when a flat structure, say a list of name/value pairs would suffice. I think JSON is popular in applications that require only simple data structures to communicate between server and client.
I never used JSON, but the simplicity described in this article intrigued me enough to want to find out more about it. For instance, how does JSON handle an object that participates in a parent-child relationship (e.g., book-has-authors or book-has-comments)? Those use-cases seem ideal for XML, since XML nicely mirrors that containment relationship.
> I respectfully submit it's time to learn how to work with > the data, not try to hide away.
I think both JSON and XML are about data, only different representations of it. I'd say, instead, that one should choose a representation that mirrors the structure of the data the closest.
In other words, the nature of the data should decide what data encoding to use, and not the preference of the developer, etc. Ideally, the data representation that mirrors the data structure the closest will also result in the biggest developer convenience.
I think people take the X(ML) in AJAX too literally. At the base it's just a technique for getting data from the server without reloading the page, and that's it! Xml was probably chosen at the beginning because it was a standard and you have parsers for it in almost any language. Therefore the implementations could be uniform.
Of course, xml does provide some nice features but nobody is stopping you from using JSON, comma-separated values or just plain text in your requests/responses. Since JSON is becoming available as an implementation in a lot of languages I don't see a reason for not using it, if it fits your application. You have to keep in mind that xml is a bigger hassle in most cases on all sides. The programming has to use certain APIs, the xml parser eats up more memory and CPU than a simple JSON parser. Also think of your application in terms of load and scalability. Xml has a lot of overhead in the size of the file being transfered in order to remain valid compared to JSON or other formats.