Introduction to Using Java, JSON, and the Spry Ajax and JavaScript Framework
Introduction
Adobe's Spry Ajax and JavaScript framework provides web application developers with a relatively easy to use collection of dynamic tags, widgets and Ajax features. Behind the scenes, Spry can use either XML or JavaScript Object Notation (JSON) as the data source for its dynamic areas and widgets. Spry can be used with any server-side technology, including Java.
In this article I'll review how to use Java to transform a collection of Java objects into a collection of JSON objects and return the JSON objects to the browser where they can be used by Spry. I'll then show a simple Spry dynamic region that creates a table that can be sorted by each column heading. The table will contain a row for each JSON object. (Updated example includes an accordion widget and data paging)
You can view an example of using Java, JSON, and Spry here: http://www.bpjava.net/JavaToJSONExample/index.jsp. You can download an archived Eclipse dynamic web project with all the source code here: /javatojsonexample/javatojsonexample.zip.
What's JSON?
JavaScript Object Notation (JSON) is a string representation of an object or a collection of objects. You can learn about JSON by visiting www.json.org. JSON can be used to exchange data between a server and a web browser. Many JavaScript libraries, including Spry, can use JSON as a data source for dynamic areas of a web page and widgets (for example a tree or grid).
Converting Java Objects to JSON
There are several libraries that make it simple to transform a collection of Java objects into an array of JSON objects. For this example I'm using the json.jar library. See http://www.json.org/java/index.html for the API. You can download the json.jar library here: /javatojsonexample/json.jar
Below is the code in the jsonexample.service.PersonService class that converts the collection of Java Person objects to an array of JSON objects. The code first gets an ArrayList (people) containing Person objects. It then loops over that collection and creates a JSON object (jsonPerson) for each Java Person object. Then the code puts that JSON object into the JSON array (jsonPeopleAry.put(jsonPerson);).
After the loop, the code creates a new JSON object using the put method that takes two arguments. The first argument is a String value that is used as the key to the second value that is a collection of JSON objects. The toString() method call then converts the entire JSON object to a plain text string.
public static String getPeopleAsJSON() {
String jsonPeopleStr = "";
ArrayList<Person> people = getPeople();
// JSON Array is used to store multiple JSON person objects
JSONArray jsonPeopleAry = new JSONArray();
try {
for (Person person: people) {
//create a JSONObject to store this person's state
JSONObject jsonPerson = new JSONObject();
jsonPerson.append("firstName", person.getFirstName());
jsonPerson.append("lastName", person.getLastName());
jsonPerson.append("email", person.getEmail());
jsonPerson.append("phoneExtension", person.getPhoneExtension() ) ;
//add this JSONObject to the JSON Array
jsonPeopleAry.put(jsonPerson);
}//end for
// Assign JSON jsonPeopleAry to jsonPeopleStr
String jsonPeopleStr = new JSONObject().put("people",jsonPeopleAry).toString();
} catch (JSONException e) {
System.out.println( e.getMessage() ) ;
}//end try...catch
return jsonPeopleStr;
}//end method getPeopleAsJSON
Using Spry and JSON
The plain text string can be returned to a browser and parsed and used by JavaScript. Adobe's Spry JavaScript and Ajax framework makes parsing and using JSON simple. There are just two steps.
- Include the Spry JavaScript libraries SpryData.js and SpryJSONDataSet.js in your page's head section
- Create a Spry data set in a JavaScript section.
<!-- include the Spry JavaScript files needed to create
a JSON data set and to use Spry region and Spry repeat -->
<InvalidTag type="text/javascript" src="js/SpryData.js"></script>
<InvalidTag type="text/javascript" src="js/SpryJSONDataSet.js"></script>
<InvalidTag type="text/javascript">
/*Create the data set using a an array of JSON objects
The String returned by Servlet getpeople is converted
into a Spry JSON data set
The parh argument specifies then name of the array of
JSON objects (see the JSON string)
*/
var dsPeople = new Spry.Data.JSONDataSet( "getpeople", {path:"people"} );
</script>
The first argument is the URL to a Java servlet that calls upon other Java classes to create the JSON array of objects and returns the String representation of that JSON array. If you view the example, you can click on a link to see this String.
Note the path value matches the value of the key (the first argument) the code used when it created the JSON object (jsonPeopleStr = new JSONObject().put("people",jsonPeopleAry).toString(); ) that was converted to a String.
Creating a Dynamic Table Using Spry
Spry has very good documentation online. To fully leverage all the Spry capabilities you should review that material. I've previously written about how to use the spry region and spry repeat attributes to dynamically display the content of a Spry data set. In this example I'm just doing something similar to create a table that can be sorted by any column heading.
Basically the code below creates a table and a row in the table for each object in the JSON data set (dsPeople). Note that the values inside the { } match the key values I used when appending each Person object's state to the JSON object (eg jsonPerson.append("firstName", person.getFirstName()); ).
<div spry:region="dsPeople">
<table class="linkTable">
<tr>
<th class="tableHeader" spry:sort="firstName">First Name</th>
<th class="tableHeader" spry:sort="lastName">Last Name</th>
<th class="tableHeader" spry:sort="email">Email</th>
<th class="tableHeader" spry:sort="phoneExtension">Phone Extension</th>
</tr>
<tr class="bottomborder" spry:repeat="dsPeople" >
<td>{firstName}</td>
<td>{lastName}</td>
<td>{email}</td>
<td>{phoneExtension}</td>
</tr>
</table>
</div>
You can learn more about how to use the spry:region and spry:repeat attributes by consulting the Spry documentation online. The basic concept is that a spry:region is tied to a Spry data source (dsPeople). The spry:repeat attribute repeats the HTML tag (in this case a table row) for each record in the data source. We can use the { } to pull out of each record a specific field's value (eg {firstName} ).
The spry:sort attribute enables dynamic sorting on that column.
Summary
Spry is just one of many JavaScript libraries that can help developer's create and populate dynamic areas of the web page. I've found Spry easier to use then some other libraries as it requires much less JavaScript knowledge. Spry comes with a good library of widgets including a built-in paging widget. Check out the Spry Samples for examples of what Spry can do. The combination of Java, JSON, and Spry can be useful for creating more robust and dynamic web applications.
There are no comments for this entry.
[Add Comment]