Monday, February 28, 2011

Working with JSON and AS3: Part 3

Today we will turn an Object into a JSON string to send to external scripts using AS3.

First of all, we import the needed class:

import com.adobe.serialization.json.JSON;

Now, we are going to create an Object called myData, which will consist of an array of 3 other Objects: member1, member2 and member3. For each member we have a set of properties, such as first and last names.

var member1:Object = new Object();
member1.firstName = "John"
member1.lastName = "Parker"
member1.age = "32"
member1.country = "Canada"
member1.job = "Programmer"

var member2:Object = new Object();
member2.firstName = "Peter"
member2.lastName = "Anderson"
member2.age = "30"
member2.country = "USA"
member2.job = "System administrator"

var member3:Object = new Object();
member3.firstName = "Bob"
member3.lastName = "Johnson"
member3.age = "35"
member3.country = "Canada"
member3.job = "Coder"

var myData:Object = {staff:[member1, member2, member3]};

Now that we have the object ready, we can use the JSON class we've imported to encode this into a string:

var myJson:String = JSON.encode(myData);

trace(myJson);

The output of the trace:

{"staff":[{"job":"Programmer","age":32,"firstName":"John","country":"Canada","lastName":"Parker"},{"job":"System administrator","age":30,"firstName":"Peter","country":"USA","lastName":"Anderson"},{"job":"Coder","age":35,"firstName":"Bob","country":"Canada","lastName":"Johnson"}]}

Where to go from here? You can, for instance, use POST method to send this JSON string to PHP or any other external script.

That's all for now.

Thanks for reading!

Related:

Working with JSON and AS3: Part 1
Working with JSON and AS3: Part 2

2 comments:

Anonymous said...

I really appreciate this blog.

Thanks for writing!

Anonymous said...

Thanks, great explanation! Helped me out!

Post a Comment