Twitter, Flex and JSON
There are libraries in several programming languages that provide access to the Twitter API. Although there’s an ActionScript 3 library for Twitter, in this tutorial we will be looking at how you can retrieve Twitter’s public timeline with a little help from another collection of ActionScript 3 utilities, the corelib library.
The result of this tutorial can be seen here (”View Source” is enabled).
Twitter’s Public Timeline
Twitter’s public timeline returns the 20 most recent statuses from non-protected users. The result is offered in four different formats (XML, JSON, RSS, Atom). The structure of the data can best be explored when we look at the XML representation of the “tweets” (Twitter speak for messages). Here’s a simplified view where the child nodes inside the status nodes have been removed:
-
<?xml version="1.0" encoding="UTF-8" ?>
-
<statuses type="array">
-
<status>
-
…
-
</status>
-
<status>
-
…
-
</status>
-
<status>
-
…
-
</status>
-
<status>
-
…
-
</status>
-
…
-
</statuses>
A single status node looks like this:
-
<status>
-
<created_at>Sat May 24 17:29:46 +0000 2008</created_at>
-
<id>819102544</id>
-
<text>I also won interview in the pageant</text>
-
<source>web</source>
-
<truncated>false</truncated>
-
<in_reply_to_status_id></in_reply_to_status_id>
-
<in_reply_to_user_id></in_reply_to_user_id>
-
<favorited>false</favorited>
-
<user>
-
<id>3725701</id>
-
<name>Kelly King Anderson</name>
-
<screen_name>startupprincess</screen_name>
-
<location>Utah County</location>
-
<description>Mentor and Friend, Make a Wish, Make it Happen!</description>
-
<profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/19834292/7355f_web_normal.jpg</profile_image_url>
-
<url>http://www.startupprincess.com</url>
-
<protected>false</protected>
-
<followers_count>206</followers_count>
-
</user>
-
</status>
As you can see, the status node contains a user node which itself has several child nodes.
corelib’s JSON Class
Of course, you could use ActionScript’s XML capabilities to manipulate and further process the XML data. In this tutorial though, we want to make use of the JSON class which is part of the ActionScript 3 corelib library and which facilitates both serialization and deserialization of JSON data.
Download the corelib library and make the corelib.swc file available to your Flex project. The JSON class is inside the com.adobe.serialization.json package. The class provides two static methods, encode() and decode(). The decode() method reads a JSON string and returns a native object as specified by the input string.
Creating the Demo Application
Our demo displays the public timeline in a datagrid. Here’s the code with some explanations below:
-
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
-
layout="absolute"
-
creationComplete="onCreationComplete()">
-
-
<mx:Script>
-
<![CDATA[
-
import mx.collections.ArrayCollection;
-
import mx.rpc.http.HTTPService;
-
import mx.rpc.events.ResultEvent;
-
import mx.rpc.events.FaultEvent;
-
import mx.formatters.DateFormatter;
-
import com.adobe.serialization.json.JSON;
-
-
[Bindable]
-
private var publicTimeline:ArrayCollection;
-
-
private function onCreationComplete():void
-
{
-
loadPublicTimeline();
-
}
-
-
private function loadPublicTimeline():void
-
{
-
twitterService.send();
-
}
-
-
private function onPublicTimelineResult( event:ResultEvent ):void
-
{
-
var rawData:String = String( event.result );
-
var arr:Array = JSON.decode( rawData ) as Array;
-
publicTimeline = new ArrayCollection( arr );
-
}
-
-
private function onPublicTimelineFault( event:FaultEvent ):void
-
{
-
trace( event.fault.toString() );
-
}
-
-
private function getFormattedDate( item:Object, column:DataGridColumn ):String
-
{
-
var dateFormatter:DateFormatter = new DateFormatter();
-
dateFormatter.formatString = "MMMM D, YYYY, J:NN:SS";
-
return dateFormatter.format( item.created_at );
-
}
-
-
private function getScreenName( item:Object, column:DataGridColumn ):String
-
{
-
return item.user.screen_name;
-
}
-
-
]]>
-
</mx:Script>
-
-
<mx:HTTPService
-
id="twitterService"
-
url="http://twitter.com/statuses/public_timeline.json"
-
resultFormat="text"
-
result="onPublicTimelineResult(event)"
-
fault="onPublicTimelineFault(event)"
-
showBusyCursor="true" />
-
-
<mx:VBox width="100%" height="100%" paddingBottom="20" paddingLeft="20" paddingRight="20" paddingTop="20">
-
<mx:Label text="Twitter Demo" fontSize="20" fontWeight="bold" />
-
<mx:DataGrid dataProvider="{ publicTimeline }" width="100%" rowCount="20">
-
<mx:columns>
-
<mx:DataGridColumn width="200" headerText="Created" labelFunction="getFormattedDate" />
-
<mx:DataGridColumn width="200" headerText="Screen Name" labelFunction="getScreenName" />
-
<mx:DataGridColumn headerText="Tweet" dataField="text" />
-
</mx:columns>
-
</mx:DataGrid>
-
<mx:Button label="Refresh" width="100" height="30" click="loadPublicTimeline()" />
-
</mx:VBox>
-
-
</mx:Application>
Lines 14-15: Twitter’s public timeline data is converted into an ArrayCollection which in turn serves as a bindable dataprovider that is used to populate the datagrid.
Lines 22-25: The loadPublicTimeline() method invokes the send() method on the HTTPService object twitterService.
Lines 27-32: The payload of the result event contains the JSON string that has been returned by the Twitter API. The decode() method converts it into an array of generic objects. The array itself is wrapped into an ArrayCollection.
Lines 39-44: This is a helper function that formats the date/time value of the created_at field.
Lines 46-49: This is another helper function that retrieves the screen_name value from the Twitter user. Please note that the user object is nested inside the status object (see the XML code above). The user object can be accessed with the usual dot syntax.
Lines 54-60: The HTTPService instance that retrieves the public timeline from Twitter’s official API URL (for more details please refer to the Twitter API documentation).
Security Restrictions
If you recreate this demo application in FlexBuilder, everything should be working fine as long as you run it from your local machine. If you put the files on your server though, you will be experiencing the “Security error accessing url” error. The reason is Twitter’s cross-domain policy. If you look at Twitter’s crossdomain.xml file, you notice that it allows access only from a very few domains.
Here’s what you have to do to get around this restriction: Replace the URL in line 56
http://twitter.com/statuses/public_timeline.json
with a URL that points to a PHP proxy file on your server:
-
<?php
-
header("Cache-Control: no-cache, must-revalidate");
-
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
-
$dataUrl = "http://twitter.com/statuses/public_timeline.json?" . microtime();
-
readfile($dataUrl);
-
?>
The PHP script simply reads the data from Twitter and writes it to the output buffer (the file header settings and microtime() are used to prevent caching).
I hope you enjoyed the tutorial. If you have any thoughts or suggestions, feel free to leave a comment below.
Tags: ActionScript, Flex, JSON, Twitter
June 9th, 2008 at 8:04 pm
Rad, thank you.
November 24th, 2008 at 10:30 am
[...] Twitter, Flex and JSON | blog.log2e.com (tags: flex) [...]
December 11th, 2008 at 6:37 am
Looks so damn great … i will try it.
Thanks for sharing