Archive for the 'Actionscript' Category

Convert Generic Objects into Class Instances using JSON Schema

Saturday, June 9th, 2007

To convert plain old Actionscript objects into Value Objects I’ve created a generator (still in internal pre alpha mode) that will take (what I call) a “JSON Schema definition” file and generate the Actionscript Value Object classes.
In the “JSON Schema definition” (like XML Schema), the data structure is declared (but unlike XSDs, this is lightweight and human readable). In fact, its valid JSON itself (so the parsing code in the generator reduces itself to a simple json.parse(…)).

You can also define nested structures (typed objects containing other typed objects) as well as typed arrays (array containing typed objects).

To proceed with an example, feed the generator the following JSON definition file:

{
  “_class”: “Book”,
  “title”: “String”,
  “author”: “String”,
  “chapters”:
  [
    {
      “_class”: “Chapter”,
      “name”: “String”,
      “pages”: “Int”
    }
  ]
}

And it will generate the following classes (package declarations omitted for readability):

public class Book
{
  public var title:String;
  public var author:String;
  public var chapters:ChapterArray;

  public function Book(o:Object)
  {
    title = o.title;
    author = o.author;
    chapters = new ChapterArray(o.chapters);
  }
}

public class Chapter
{
  public var name:String;
  public var pages:int;

  public function Chapter(o:Object)
  {
    name = o.name;
    pages = o.pages;
  }
}

public dynamic class ChapterArray extends Array
{
  public function ChapterArray(o:Object)
  {
    super();
    for each(var item:Object in o)
    {
      var chapter:Chapter = new Chapter(item);
      this.push(chapter);
    }
  }
}

Now all you have to do when receiving plain old objects (via a webservice, json/http or any other method), all you have to do to convert them to typed objects is to call

var book:Book = new Book(event.result);

And you’ll have all the benefits of having typed objects (like complete IDE support, etc.) as well as having your interface documented!

I’m interested in feedback about this method, so feel invited to comment.

Close
E-mail It
Socialized through Gregarious 42