Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

actionscript 3 and JSON

I've been trying to get JSON working with AS3 for a while now, but to no avail. I keep getting the following error when I get the JSON back:

TypeError: Error #1034: Type Coercion failed: cannot convert Object@26331c41 to Array.

I've tried changing the datatype of the variable "jsonData" to object, which fixes the error, but I'm not entirely sure how I can parse the data.

package 
{
    import flash.display.Sprite;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.events.*;
    import com.adobe.serialization.json.JSON; 

    public class DataGrab extends Sprite {

        public function DataGrab() {

        }

        public function init(resource:String):void {
            var loader:URLLoader = new URLLoader();
            var request:URLRequest = new URLRequest(resource);
            loader.addEventListener(Event.COMPLETE, onComplete);
            loader.load(request);
        }   

        private function onComplete(e:Event):void {
            var loader:URLLoader = URLLoader(e.target);
            var jsonData:Array = JSON.decode(loader.data);
            trace(jsonData);
        }


    }
}
like image 806
minimalpop Avatar asked Oct 31 '09 05:10

minimalpop


People also ask

What ActionScript 3?

ActionScript 3 is an object-oriented programming language originally created by Macromedia Inc., which continued to evolve after being acquired by Adobe Systems. It is a superset of the ECMAScript standard (more widely known as JavaScript) with a stronger focus on classes, interfaces, and objects.

What is JSON for?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

Is ActionScript free?

The language itself is open-source in that its specification is offered free of charge and both an open source compiler (as part of Apache Flex) and open source virtual machine (Tamarin) are available. ActionScript was also used with Scaleform GFx for the development of 3D video game user interfaces and HUDs.


1 Answers

You were correct when you had the jsonData variable as an Object. To iterate through all the properties of that variable you could just do something like this:

var jsonData:Object = JSON.decode(loader.data);
for (var i:String in jsonData)
{
    trace(i + ": " + jsonData[i]);
}

If you wanted to check if the object contained a specific property you could use something like:

var hasFooProperty:Boolean = jsonData.hasOwnProperty("fooProperty");
like image 138
Raul Agrait Avatar answered Nov 15 '22 23:11

Raul Agrait