How to decode and cast JSON string in Flex?
Solution 1
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.
Solution 2
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.
Solution 3
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
I'm a full stack developer (.Net/NodeJS) specialized in data security. Open source projects: https://github.com/eranbetzalel Code snippets: https://gist.github.com/eranbetzalel
Updated on June 24, 2022Comments
-
Eran Betzalel about 2 years
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
classpublic 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?