Time for action - deserializing a JSON object

Adobe's as3corelib library contains a set of utility classes for serializing and deserializing JSON. It's available at http://github.com/mikechambers/as3corelib, but you don't need to download it, as it is already included in the \src\ directory of the project. (It consists of every class in com.adobe.*)

  1. In CustomGraphContainerController.as, import the JSON class:
    import com.adobe.serialization.json.JSON;
    
  2. Modify the onGraphDataLoadComplete() function so that it deserializes the JSON string to an object, instead of simply tracing the string:
    private function onGraphDataLoadComplete(a_event:Event):void
    {
    var loader:URLLoader = a_event.target as URLLoader;
    //obtain whatever data was loaded, and trace it
    var graphData:String = loader.data;
    var decodedJSON:Object = JSON.decode(graphData);
    }
    
  3. Trace the name property of this new object, to check that it worked:
    private function onGraphDataLoadComplete(a_event:Event):void
    {
    var loader:URLLoader = a_event.target as URLLoader;
    //obtain whatever data was loaded, and trace it
    var graphData:String = loader.data;
    var deserialisedJSON:Object = JSON.decode(graphData);
    trace("name:", decodedJSON.name);
    }
    
  4. Compile and run the SWF. Resulting output:
    name: Packt Publishing
    

What just happened?

We passed this string to the JSON.decode() method:

{
"id": "204603129458",
"name": "Packt Publishing",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/ hs302.ash1/23274_204603129458_7460_s.jpg",
"link": "http://www.facebook.com/PacktPub",
"category": "Products_other",
"username": "PacktPub",
"company_overview": "Packt is a modern, IT focused book publisher, specializing in producing cutting-edge books for communities of developers, administrators, and newbies alike.\n\nPackt published its first book, Mastering phpMyAdmin for MySQL Management in April 2004.",
"fan_count": 412
}

and it turned the string into a native AS3 object, as if we had typed this:

var graphObject:Object = {};
graphObject.id = "204603129458";
graphObject.name = "Packt Publishing";
graphObject.picture = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs302.ash1/23274_204603129458_7460_s.jpg";
graphObject.link = "http://www.facebook.com/PacktPub";
graphObject.category = "Products_other";
graphObject.username = "PacktPub";
graphObject.company_overview = "Packt is a modern, IT focused book publisher, specializing in producing cutting-edge books for communities of developers, administrators, and newbies alike.\n\nPackt published its first book, Mastering phpMyAdmin for MySQL Management in April 2004."
graphObject.fan_count = 412;

(Note that unlike the raw string we had earlier, the slashes in the URLs have not been escaped.)

This means we can easily access any of the information Facebook has about this Page, or even iterate through every piece of data.