Tuesday, January 03, 2012

How to create typed AS3 objects from JSON

JSON is very simple and convenient format for communication between Adobe Flash/Flex client and server side. as3corelib library contains class for JSON deserialization from String to Object. It's not good idea to use simple Object because you cannot use Bindable tag in Flex application. Re-factoring will be nightmare for you without typed objects. To solve that problem I created util class to convert Object into typed one. Source code you can see on gist: https://gist.github.com/1556693. I have MessageVO.as class with two attributes: data and type. Type contains information about data. For example, if type equals "user" it means that data will contains object of UserVO class.
public class MessageVO {
    public var type:String;
    public var data:Object;
}
...
[Bindable]
public class UserVO {
    public var id:Number;
    public var nickname:String;
}

To convert object into typed object you should execute the following code:

    var object:* = Converter.convertData(jsonObject, UserVO);

In my project I use dictionary where key is type (string) and value is class. For example:
    var typeToClassMap:Dictionary = new Dictionary;
    ...
    typeToClassMap["user", UserVO];
    typeToClassMap["chatMessage", ChatMessageVO];
    ...
    var jsonObject = JSON.decode(jsonString);
    var object:* = Converter.convertData(jsonObject.data, typeToClassMap[jsonObject.type]);

object variable will contain typed object converted from jsonObject.

2 comments:

Marcos W said...

Hi,
congratulations for this very useful class, but i'm having a problem. If i change the ID type to INT, it can't cast anymore. I'm trying to look for this solution, but i've lost too much time on this ... could you please test if this is a bug or if the problem is with me ?

Tnks

Marcos W said...

Found the problem ...and it was with me
=)

I did not see this line

private static var _simpleTypes: Array = [Boolean, Number, String];

So i add the INT on it and works!!

Tnks