Total Pageviews

Thursday 16 June 2011

JSON and AS3 Communication

JSON is also reffered as JavaScript Object Notation (JSON).

JSON is a lightweight text-based data exchanging standart designed to be easy readable for humans. It came from the Java Script programming language and represents simple associative arrays. Even though it has Javascript in its name, it is very widely used in all programming languages, mainly to transfer data between a server and a web application.

JSON takes 25% space rather than XML file.

To parse JSON using AS3, I will use some classes from the library written by the good Adobe people
called as3corelib.

The example JSON file which i am using have structure like this:

{
"staff":
[
 {
 "firstName":"John",
 "lastName":"Parker",
 "age":"32",
 "country":"Canada",
 "job":"Programmer"
 },

 {
 "firstName":"Peter",
 "lastName":"Anderson",
 "age":"30",
 "country":"USA",
 "job":"System administrator"
 },

 {
 "firstName":"Bob",
 "lastName":"Johnson",
 "age":"35",
 "country":"Canada",
 "job":"Coder"
 }
]
}
 
Now, let's parse it using AS3.
// import the necessary JSON class (I have the com folder in the 
same directory as my flash code):
 
package
{
 import com.adobe.serialization.json.JSON;  
 import flash.display.*;
 import flash.events.*;
 import flash.net.*;
 
 public class MyClass extends MovieClip
 {
  public function MyClass()
  {
   var myRequest:URLRequest = new URLRequest("staff.txt");
   var myLoader = new URLLoader();
   myLoader.addEventListener(Event.COMPLETE, onload);
   myLoader.load(myRequest);
   
/*which will consist of an array of 3 other Objects: myData,
For each member we have a set of properties, such as first and 
last names.use the JSON class we've imported 
to encode this into a string:*/
function onload(evt:Event):void
   {
    var myData:Object = JSON.decode(myLoader.data);
    trace(myData.staff[0].firstName);
    trace(myData.staff[1].job);
    trace(myData.staff[1].age);    
   }
  }
 }
}

No comments:

Post a Comment

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...