Eran Betzalel
Eran Betzalel

Reputation: 4193

How to decode and cast JSON string in Flex?

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?

Upvotes: 5

Views: 14590

Answers (4)

shi11i
shi11i

Reputation: 1548

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 );

Upvotes: 0

Bernesto
Bernesto

Reputation: 1436

FYI if you are just doing JSON decoding, and it is a Flex app, not AIR. You do not need the as3Corelib package to do so. You can just use the parent browser's JavaScript interpreter like this:

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

This might save your user a few Kb on the download.

Upvotes: 2

Eran Betzalel
Eran Betzalel

Reputation: 4193

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".

Upvotes: 1

Glenn
Glenn

Reputation: 5342

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.

Upvotes: 3

Related Questions