Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 298
Eran Betzalel Avatar asked Sep 20 '09 01:09

Eran Betzalel


1 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/

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.

like image 75
Glenn Avatar answered Oct 21 '22 16:10

Glenn