0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this is the solution i went for because it is the easiest at the time. however i did create a copy method for more complex objects. thanks!
0

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)   {}
        }
    }       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.