Change is in the Air
Let's get into some specifics regarding the JSON standard.
|Syntax||String Example||or||Numeric Example|
|"key": value||"name": "Fred"||"price": 55.99|
JSON supports several data types including:
- number (integer, real, or floating point)
- String (double-quoted Unicode with backslash escapement)
- boolean (true and false)
- Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
- Object (collection of key/value pairs, comma-separated and enclosed in curly brackets)
Here is a sample JSON object demonstrating various data types:
Note how few characters are used. Now that's compact!
Taking JSON for a Test Drive
A common use for JSON is to pass objects between the Web page and a server-side application. In the following JSP example, a simple JSON object is constructed using the JSON Object utility class from the JSON.org home page.
The above code would send the following String to the browser. For illustration purposes, the sequence of the key-value pairs follows the same order in which they were added to the JSONObject. In practice, this wouldn't necessarily be the case, but is of no consequence; like hash tables, element ordering is a non-issue:
It can even be simpler than that! The JSONObject utility class has a constructor that accepts a Plain Old Java Object (POJO) class and a String Array. It uses class reflection to convert the public members in the Array to JSON properties. Here's how you would use the constructor:
Of course JSON works just as well going the other way. Again, there are plenty of utility scripts to choose from. As an example, here's one called JSON.js by Andrea Giammarchi. To use it, you simply call the encode function on your object like so:
Alternatively, you can create your own function by adding the JSON.encode() function to the Object prototype:
The encode's sister decode() function can then be used to parse the server response: