The JSONObject class: For reading and writing JSON in ActionScript +
Back in February while working on an AIR application, I found myself dealing with a lot of JSON data in ActionScript. I was using the corelib library for parsing and generating JSON objects. It was all good until I realized I could improve it even further.
While the JSON class does its job perfectly well, it has one small drawback: it’s not object-oriented.
The static methods encode and decode take the data object as input and return a converted data object as output. The objects themselves have no knowledge of the conversion from JSON to ActionScript and back; they’re just dumb objects. Every time you want to generate a JSON string out of an ActionScript object, you have to invoke the encode method; every time you want to parse a JSON string into an ActionScript object, you have to invoke the decode method. That’s procedural programming. How about if the objects themselves knew how to do this conversion?
Enter the JSONObject class.
Instances of the JSONObject class can read and write JSON strings while at the same time serving up their data as ActionScript properties.
Let’s look at an example:
var data:String = "{\"name\":\"John Doe\",\"age\":28}";
var person:JSONObject = new JSONObject(data);
trace(person.name); // John Doe
trace(person.age); // 28
person.age++;
var newData:String = String(person);
trace(newData); // {"name":"John Doe","age":29}
A few things to notice:
- A
JSONObjectinstance can be created by passing the JSON string to the constructor. If the JSON string is not available at the time of construction, the object can be populated later using thepopulatemethod. - You can access the properties of the JSON object directly as properties of the
JSONObjectobject. - A
JSONObjectobject can be converted to a JSON string by simply casting it to theStringtype.
The most important benefit of using the JSONObject class is that it provides strong typing for “JSON objects” in your system.
// Methods for JSON I/O
function readJSONObject():JSONObject;
function writeJSONObject(jsonObject:JSONObject):void;
You can also create concrete types to accurately represent objects in your system. For instance, the piece of JSON data in the above example could be represented as a Person object.
public class Person extends JSONObject
{
public function Person(data:String)
{
super(data);
}
public function get name():String
{
return super.flash_proxy::getProperty("name");
}
public function get age():int
{
return super.flash_proxy::getProperty("age");
}
}
Another benefit is that it becomes easy to debug code by examining the contents of a JSON object.
trace(person); // prints object in JSON format
I haven’t reinvented the wheel here. The class internally uses the same JSON class from the corelib library. It’s just an OO wrapper.
Source: JSONObject.as