Here is how to get Data from Server in Adobe AIR based applications.
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
applicationComplete="init()"
width="620" height="740"
frameRate="30">
<fx:Script>
<![CDATA[
import com.adobe.serialization.json.JSON;
// var ini
// ------------------------------------------------------------------------
private var filePath:String = "http://www.mysite.com/test.php?callback=?";// URL or path to JSON Source // can be "assest/jsondata.txt";
private var urlLoader:URLLoader;
private var jsonDataArray:Array;
private var jsonObj:Object;
private var request:URLRequest;
private var variables:URLVariables;
private var requestFilters:String;
private var requestHeaders:Array;//used for content-type headers and such
private var arr:Array = new Array();// saving all objects to dataGrid
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private function init():void
{
requestHeaders = new Array(new URLRequestHeader("content-type","application/json"));//add as many comma separated headers as you need to send to server
// Add event listener for button click
btn.addEventListener(MouseEvent.CLICK,loadJSONData);
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private function loadJSONData(e:MouseEvent=null):void
{
// Load file
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, fileLoaded,false,0,true);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, fileLoadFailed);
request = new URLRequest();
request.method = URLRequestMethod.POST;//use URLRequestMethod.GET if you want
request.requestHeaders = requestHeaders;//headers to send
request.data = 'jsonCallback';//can send data/parameters with this request to server. If server requires data/parameters sent as JSON string, you can accomplish it passing JSON String like this: request.data = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": { "filter" : {} }, "id": 1}';
request.url = filePath;
urlLoader.load(request);
}
// ------------------------------------------------------------------------
private function fileLoadFailed(e:Event):void
{
trace("Failed: "+e.target.data.toString());
}
// ------------------------------------------------------------------------
private function fileLoaded(e:Event):void
{
// Clean up file load event listeners
urlLoader.removeEventListener(Event.COMPLETE, fileLoaded);
// If you wanted to get the data from the event use the line below
//var urlLoader:URLLoader = URLLoader(event.target);
trace("urlLoader.data: "+urlLoader.data+", Data type: "+typeof(urlLoader.data));
var Obj:Object = urlLoader.data;
// Parse the response to get Array or Object depending on how the JSON is formatted on Server.
//jsonDataArray = com.adobe.serialization.json.JSON.decode(urlLoader.data);
// converts urlLoader.data to a localized Object or Array
// check if the returned data is an Object
if(typeof(com.adobe.serialization.json.JSON.decode(urlLoader.data))=='object')
jsonObj = com.adobe.serialization.json.JSON.decode(urlLoader.data);
// if data returned is an Array
else if(typeof(com.adobe.serialization.json.JSON.decode(urlLoader.data))=='object' && com.adobe.serialization.json.JSON.decode(urlLoader.data).length>2)
jsonDataArray = com.adobe.serialization.json.JSON.decode(urlLoader.data);
/* Your Data Format
{
"sites":
[
{
"siteName": "JQUERY4U",
"domainName": "http://www.jquery4u.com",
"description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
},
{
"siteName": "BLOGOOLA",
"domainName": "http://www.blogoola.com",
"description": "Expose your blog to millions and increase your audience."
},
{
"siteName": "PHPSCRIPTS4U",
"domainName": "http://www.phpscripts4u.com",
"description": "The Blog of Enthusiastic PHP Scripters"
}
]
}
*/
// now you should be able to access the data like this:
trace(jsonObj.sites[0].domainName);
// or
trace(jsonDataArray[0].siteName);
// Now you can loop through your received data as usual.
}
// ------------------------------------------------------------------------
]]>
</fx:Script>
<mx:DataGrid id="dg" top="100" width="600" height="600" horizontalCenter="0">
<mx:columns>
<mx:DataGridColumn width="200" dataField="name" headerText="Name"/>
<mx:DataGridColumn dataField="value" headerText="Value"/>
</mx:columns>
</mx:DataGrid>
<mx:Label top="15" color="#0D595A" fontSize="30" fontWeight="bold" horizontalCenter="4"
text="Get JSON Data From Server"/>
<mx:Button id="btn" top="70" width="200" label="Get JSON Data from Server"
chromeColor="#A7FEFF" fontWeight="bold" horizontalCenter="0"/>
</s:WindowedApplication>
Now this one is the complete code to get you started with Adobe AIR App that loads JSON Data from Server.
I'm using import com.adobe.serialization.json.JSON;
in this example. And it needs to be included to parse/decode JSON Data received in String format to Local ActionScript Object.
You can Download as3corelib
from GITHUB.
If you are using Adobe Flash to create your AIR App, then you must include this library in your Libraries/Source paths.
If you're using Adobe Flash Builder 4.6 Premium as am I, then:
1) In Adobe Flash Builder make sure you're in Flash Builder Perspective, from Package Explorer, Right-Click your Project and Select Properties. (This will Open up your Projects Properties)
2) In the Properties Dialogue of your Project, Select "Flex Build Path".
3) In "Flex Build Path" Dialogue, Select the Tab: "Library path".
4) Click "Add SWC" button on the Right side. And browse to the location of: "as3corelib.swc" file. (better if you place this file in "libs" folder/directory in your Applications main directory, where "bin-debug" directory also resides.) Now Select the file and click OK button.
5) Again click OK button to close the Project's Properties Dialogue Box.
6) Now save your all project files and everything, and close Flash Builder.
7) Now Restart Flash Builder. Run or Debug your Project. You should be able to see output of our trace
statements in Console Log.
8) If there are Errors when compiling your Project, then you must also include the com.adobe.serialization.json.JSON;
package in your Project's "src" directory, by uncompressing the Zip file that includes the Source ActionScript Classes for the as3corelib.
9) Now it should work. Better restart Flash Builder again. Now your Project's SRC directory should have a com directory which includes other Directories and ActionScript Classes of the as3corelib package. (At least I have no problem now that I have added as3corelib.swc and the source files of the package)
Download the "as3corelib" here on github. It contains the as3corelib.swc file in lib directory and ActionScript 3.0 source classes of com.adobe.serialization.json
package in src directory. (You might need to copy the com directory with all contents to libs directory in your Project's root directory. So that You can call its decode and encode methods in your code and will be compiled in to your SWF and AIR files.)