Wednesday, January 25, 2012

JSON

JSON = Javascript Object Notation

JSON is a convention for representing objects as Strings.

For example, a JSON string:
{"firstName":"Andrew","lastName":"Weber"}

represents a object whose firstName field has the value "Andrew" and the lastName field has the value "Weber".

We can specify Lists as well. So:
{"firstName":"Andrew","lastName":"Weber", "children":["Donna","Carol","Tyler"]}

represents the same object, with an additional specification for a field "children" which is a List and has the elements "Donna", "Carol" and "Tyler".

JSON has conventions for specifying maps as well, and you can have JSON objects inside other JSON objects.

So why is all this useful??!

Often you need to pass a Java object to the View (jsp) where a javascript will present the object.

It is very easy to "stringify" the Java object into JSON and pass it to the javascript. The javascript can then unmarshal the JSON string into a JAVASCRIPT object and use it.

Each side, Java and javascript, get to work with their native objects - and JSON provides a way to squirrel objects back and forth between the two.

There are standard JSON libraries already available, both in Java and javascript, which make it a breeze to stringify and unmarshal objects.

The other alternative to JSON is using XML to transfer objects. But JSON is way more lightweight and better suited for transferring tiny objects. XML is better when large amount of data needs to be transferred, for example transferring large number of records from a database.

No comments: