views:

1386

answers:

3

I'm using as3corelib to decode/encode JSON strings. In my little experiment I want to encode an object (UserInfo) to JSON string and decode it back to the object, however it seems to fail at the convertion point (the last line), why would that happen? how can I make it work?

The UserInfo class

public class UserInfo
{
    public var levelProgress    : int;
}

The conversion code

var user1:UserInfo = new UserInfo() 
user1.levelProgress = 20;

var a:String = JSON.encode(user1);
var b:Object = JSON.decode(a);
var c:UserInfo;

c = b as UserInfo;  // c gets null, why?
+1  A: 

You need to do something similar to what this page says: http://benrimbey.wordpress.com/2009/06/20/reflection-based-json-validation-with-vo-structs/

The problem with your code is you are trying to downcast a native Object into a specific Class instance that it knows nothing about. The structures of your two types are different. UserInfo inherits from Object (in a sort of funky AS3 way because of the way Classes are compiled), but b is a simple Object.

Glenn
A: 

Glenn's link really did the trick. I also added a conversion between dot-net and AS3 - it seems that dot-net writes the __type attribute like so: "Class:Namespace", but AS3 needs it to be like so: "Namespace.Class".

private static function convertDotNetToASNameType(nameType:String):String            
{
    return(nameType.split(':').reverse().join('.'));
}

BTW, if you are using Glenn's link and a WCF server, be sure to replace "clientClassPath" with dot-net's "__type".

Eran Betzalel
A: 

Could also do the casting in the VO's constructor.

public class YourVO
{

    public var id:int;
    public var prop1:String;
    public var prop2:String;
    public var prop3:String;

    public function YourVO(jsonObject : Object)
    {
        for (var p:String in jsonObject) {
            if( this.hasOwnProperty(p) ){
                this[p] = jsonObject[p];
            }
        }
    }

}

and use it like so: var yourVO:YourVO = new YourVO( jsonObject );

shi11i