Sunday 7 December 2008

JSON, Java and JavaScript

JSON is so simple there's not a lot to say about it, but I thought it's worth putting up a few links and notes for reference.

JSON is JavaScript Object Notation. Whilst it could be called an Object Notation (a simple one), it's not tied to JavaScript, although it's early origins are from that language (ECMAScript, ECMA-262 3rd Edition). JSON is essentially language independant, like XML. JSON, like XML can represent data structures and data (self describing) but unlike XML, JSON does not support namespaces, schema and other more advanced features. JSONs key strengths are its simpicity and low overhead, terse message size.


JSON looks like this:


{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}


Where { and } contain the object, the properties are listed as "name" : "value" pairs. Objects can be embedded within objects and arrays are denoted using comma separated lists within []

So, special symbols (for escaping) are: {}[]:"

Main Site: http://www.json.org/

Simple JSON for Java: http://www.JSON.org/java/json_simple.zip http://www.json.org/java/simple.txt

Simple JSON for JavaScript: http://www.json.org/js.html

Wikipedia: http://en.wikipedia.org/wiki/JSON


JavaScript:

Basic suppport for converting JSON messages into objects (deserialisation) is to use the often best avoided eval function, as follows:

var myObject = eval('(' + myJSONtext + ')');

where the outer '(' ')' are necessary for the JavaScript language, not JSON itself.

Better (safer) still, various libaries are available, such as the Open Source version from www.json.org in json2.js

Which essentially is used like this:

var myObject = JSON.parse(myJSONtext, reviver);

var myJSONText = JSON.stringify(myObject, replacer);


Java:

Create a JSON string using org.json.simple.JSONObject:

JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
System.out.print(obj);

The toString() on the JSONObject serialises the JSON object (map of name value pairs) to a JSON string.

JSON is simple, by design, so there isn't much more to be said on it.

One of the main things to watch out for is encoding/escaping messages so they are JSON friendly, I'll add more on that soon.

The following link may be useful when working with character escaping: http://www.the-art-of-web.com/javascript/escape/

.

No comments: