Friday, December 14, 2007

What the Heck is JSON!?!

That was my question when I first came across JSON. What the heck is JSON, and why didn't I know it?

The quick definition is that JSON stands for JavaScript Object Notation. Of course, that doesn't really tell you much. Now you know what JSON stands for, but what does it really mean?

Come on, man, tell us. What does it mean?

The bottom line is that JSON is a lightweight data-interchange format. In English, that means that JSON is an simple and elegant method of moving data from one point to another.

Sound familiar? Are all you XML enthusiasts standing up, pumping your fists and screaming "Mother of God! My power....my power...it's slipping away. What's wrong with this world? Dear God, what's wrong with this world..."?

Well, sit down and take a deep breath. JSON isn't going to replace XML. JSON isn't going to go away, either.

JSON's strength is in it's simplicity. It is essentially either an unordered set of name/value pairs, or it is an ordered collection of values. That's it. Nothing more. The JSON clan claims that this is set in stone. There will never be anything more. No schema. No comments. No headache. Just simple data that you can move from point a to point b.

Ah, simplicity, I love you so....

I hear you. You want me to stop the yapping and show JSON in action. Well, here you go. We're going to use some code from a VE implementation. The code below is a server-side code snippet for getting some search results from MapPoint. This data will be consumed on the client so our job is to convert the data to JSON and send it upstream as a string. Ready? Okay!

/*...remember, this is inside a method on the server...most likely in a web service or a library called by the web service*/
FindResults fss = this.findService.FindAddress(fas);
JavaScriptSerializer s = new JavaScriptSerializer();
string json = s.Serialize(fss);
return json.ToString();


Whew! That JSON sure is hard work! The key is using the JavaScriptSerializer. That bad boy takes my collection of results objects and serializes it into a JSON collection of objects. Bing, bang, boom. Done.

Now let's see how we consume it on the client.

function WebMethodCallback(result, eventArgs)
{
var data;

try
{
data = eval('(' + result + ')');
var numberFound = data.NumberFound;

}
catch(e)
{
//handle this exception
}
}


Again, that's it! We eval the string into an object we called data. From that point forward, data is used just like any other object. Notice on the next line we set an local variable to a property off of the data object. Shazam! JSON in action, baby.

No comments: