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.