How to decode and cast a JSON string in Flex?

I am using as3corelib to decode / encode JSON strings. In my little experiment, I want to encode object ( UserInfo) into a JSON string and decode it back to the object, however it doesn't seem to work at the jump point (last line), why is this happening? how can i make it work?

Class UserInfo

public class UserInfo
{
    public var levelProgress    : int;
}

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?
+5
source share
4 answers

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/

, , . . UserInfo Object ( AS3 - , ), b - .

+3

FYI, JSON, Flex, AIR. as3Corelib. JavaScript- :

var myJSONString:String = "{name:'Joe',age:35}"; var myObj:Object = ExternalInterface.call('eval', "("+myJSONString+")");

.

+2

. dot-net AS3 - , dot-net __type, : "Class: Namespace", AS3 , : "Namespace.Class".

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

, Glenn WCF, "clientClassPath" dot-net "__type".

+1
source

You can also cast in the VO 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 this:

var yourVO:YourVO = new YourVO( jsonObject );
0
source

All Articles