dev.e.loper
dev.e.loper

Reputation: 36034

Actionscript - JSON to complex object

I'm trying to JSON encode and decode a flash.geom.Rectange object. When I decode the object, it is of type Object. If I try to cast it to Rectangle, I get a null object:

var rect:Rectangle = JSON.decode(json_string) as Rectangle;

It looks like I can't cast to a Rectangle from Object that has exactly same properties as Rectangle.

An option would be to copy properties from Object to Rectangle.

I'm looking at introspection of objects however, iterating through object's properties only goes one level deep. If an a property that is being copied is of type Point, the Point's properties are not copied. Looks like I have to copy them recursively.

Is there a function in actionscript that would deep copy an object?

Upvotes: 0

Views: 120

Answers (2)

dev.e.loper
dev.e.loper

Reputation: 36034

Here is a copy function that I came up with. Tested it with a simple type like Rectangle. There is a try/catch statement there because I was getting exceptions when I would try to write to read-only properties. There should be an if statement to check if property is writable but I don't have the time or patience right now. I will come back to improve it later but for now here it is:

public static function copy(source:Object, dest:Object):void
{
    for (var prop in source)
    {
        if (getQualifiedClassName(source[prop]) == "Object")
        {
            copy(source[prop], dest[prop]);
        }
        else
        {
            try // bad. should really be an if statement to check if property is writable. 
            {
                dest[prop] = source[prop];
            }
            catch (err:Error)   {}
        }
    }       
}

Upvotes: 0

Mike Bedar
Mike Bedar

Reputation: 910

Short Answer - No. You'll have to pass the components of the decoded JSON object into a new Rectangle.

var jRect:Object = JSON.decode(json_string);
var rect:Rectangle = new Rectangle(jRect.x, jRect.y, jRect.width, jRect.height);

In this case you are lucky because the Points you mentioned are inferred from the constructor values. For more complex classes I usually make a class level fromJSON method.

Upvotes: 4

Related Questions