Flash CS3, ActionScript 3.0, JSON keep it simple tutorial

39 Responses to “Flash CS3, ActionScript 3.0, JSON keep it simple tutorial”

  1. Alan Green Says:

    Do you even try to compile the crap you post?

  2. Andres Says:

    Okay, made some minor corrections so it should now work as simple as possible and on frame 1 in Flash CS 3. And Alan Green, chill out dude. If you can now find something better on the net, as simple as this, and targeted towards beginners, let me know.

  3. www.johannes-erhardt.de » Blog Archive » JSON in ActionScript 3 Says:

    [...] Winklite – Flash CS3, ActionScript 3.0, JSON keep it simple tutorial [...]

  4. Scott Barr Says:

    Nice article. Just a small correction to make.

    The contents of the file should be as follows. You have the phone for Jenny instead of number.

    [ {”name”:"Jaylo", "number":"3243251"}, {"name":"Jenny", "number":"8675309"}]

  5. EV Says:

    HELP, I try this but it dosnt work, could you email me the files, I am really trying to fing resources on json and as3 but dont find that much online. do have more examples you can post or email me.

    Thanks

  6. Andres Says:

    What kind of errors are you getting? Also, note the typo Scott Barr caught in his comment. See if that helps.

  7. greg Says:

    Thanks for this tutorial. One newbie step I don’t understand is: how do I actually load the as3 corelib into my .fla? I downloaded it, but I don’t see anyway from the flash IDE to import it and trying to use

    import com.adobe.serialization.json.JSON;

    throws compiler errors

    Thanks!

  8. greg Says:

    Never mind. I figured it out. “Installing as3 corelib” means copying everything in the corelib/src directory into thesame dir as my .fla. Kinda obvious. Kinda retarded. And this seems to be the only place on the internet that piece of knowledge is written down.

  9. Andres Says:

    Hi Greg, what kind of compile errors are you getting? Also, you shouldn’t have to load anything via the IDE as long as your import statement in your main document is well structured to match the path to the folder where the JSON class resides. Morever, make sure the JSON class itself expresses its own location after your package statement *but only up until the folder name*. E.g.

    import com.adobe.serialization.json.JSON ; //in main file, which points to /com/adobe/serialization/json

    package com.adobe.serialization.json… //In JSON.as which points to its own loaction but only up to the folder not the actual JSON class.

    Hope this helps and thanks for your comment.

  10. Brad Rice Says:

    That was very helpful. I like that you kept is simple. I had to change it from an array to an object so I could call based upon a key.

    var HotSpots:Object; //instead of array

    //json ojbect looked like this

    {“its_hs”:{“name”:”its_hs”, “url”:”http://www.uakron.edu/its”}, “sa_hs”:{“name”:”sa_hs”, “url”:”https://www.uakron.edu/sa”}}

    It worked good.

  11. RutgerB Says:

    Hi,
    Thnx for the tutorial, however I have been struggling with with a “1120: Access of undefined property JSON.” error for a few hours now and cant seem to find a solution anywhere. Anyone any pointers?

  12. Andres Says:

    Hi Rutger,

    Do you know what file is throwing the error? Also, can you provide a snippet of line 1120?

    Thanks,

    -A

  13. RutgerB Says:

    While preparing a demo package for the error I got the thing working! Somehow I must have missed something in my original package. I’ll take another look at it tomorrow and post what went wrong.
    Thnx for the fast reply btw:)

  14. RutgerB Says:

    Just tried my demo package on another computer and I have the error again.
    var myObject:Object = JSON.decode( rawData );
    Causes:
    1120: Access of undefined property JSON.

    Here’s the package http://rutgerb.com/flashjson/flashjson.rar

    What am I missing? The package worked on my other machine.

  15. Andres Says:

    Hmmm, everything looks to be in order and it’s working fine on my box… Any particular differences between both machines?

  16. RutgerB Says:

    Ok, I think I solved it.

    I tried different JSON implementations for flash before landing on your page. I apparently left a JSON.as file in the root, after deleting it everything worked!

    Thanks for your help though.

  17. Andres Says:

    np

  18. Alia Says:

    Hi,

    Can you include a bundle of the example file in a folder to download and run?
    Thanks for your help!

  19. Andres Says:

    Hi Alia,

    The nicest implementation I’ve seen so far is the one submitted above by RutgerB, I’d suggest taking a look at that one (and it does work).

    Thanks,

    -A

  20. Alia Says:

    Hi Andres,

    yes, I tried to run it. It works fine but RutgerB implemented it in the Flashjson.as file.
    How would it look like in a normal actionscript in a .fla file? What would change?
    Thanks in advance!

  21. Andres Says:

    Hi Alia,

    You can now download the example here http://www.andresnarvaez.com/examples/flash/flashAndJSONexample.zip also available at the end of the article.

    Thanks, and let me know how it goes.

    -A

  22. Alia Says:

    Hi Andres,

    It works brilliantly, Thanks!
    A basic json tutorial for flash is scares, good that I stumbled upon your blog!

    Alia

  23. Alia Says:

    Hi Andres,

    I have another question. Is it possible to get a string:value pair without knowing the string name, for example from your numbers.txt data, I would like to know the second pair (string and value) from the first object (i.e. “number”:”3243251″).
    I cannot do a Object.string because I do not know the string name.

    Is this possible?

    Thanks! Really appreciate it!

    Alia

  24. Andres Says:

    Hi Alia,

    Well, you could do this [{"name":"Jaylo"}, {"number":"3243251"}, {"name":"Jenny"}, {"number":"8675309"}] or this (in order to maintain the logical grouping of your key/value pairs) [[{"name":"Jaylo"}, {"number":"3243251"}], [{"name":"Jenny"}, {"number":"8675309"}]] and you’ll get to your key/value pairs “still in the form of an object” via Object[1] and Object[0][1] (respectively); however, you’ll still need the string name if you wish to output the value (e.g. Object[0][1].number). If you actually wish to output your key and value pair, then the only way I’m seeing right now is via a for in loop (using my original numbers.txt example):

    for (var key1:Object in People) {

    for (var key2:Object in People[key1]) {

    trace(key2) ;
    trace(People[key1][key2]) ;

    }
    }

    If you only want a specific pair, you could abstract the above into a helper function that sets a counter outside of the loop, increments the counter at the end of the loop, then you pass a flag as parameter that would be tested against the counter each iteration and would eventually cause the loop to return out of the function… works debug wise but doesn’t feel so good production wise. There might already be something like this in AS3 that does the same, most of the above is based on my experience w/ JS. Hope this helps and let us know if you find anything.

    Thanks,

    -A

  25. Skip Says:

    Hello. Thank you for this example, I think it is exactly what I need to get started with JSON. I have a basic question about adding this library to Flash. When I extract the core lib the root dir is as3corelib-.92.1 From there it branches into numerous subdirs.

    I have flash installed at C:\Adobe Flash CS3. Where is the best place to put the core lib ? It looks like most of the default classes are in C:\Adobe Flash CS3\en\configuration\ActionScript 3.0\classes. Should I put this lib there as well ?

  26. Andres Says:

    Good question, I think it’s really up to you as long as your file paths are written correctly in your import statement within the main file and in the json package itself and your directory structure organized to make sense.

    Now, going your way, I’d throw the serialization folder in classes/fl/, so it’s at par with the other utility class folders (e.g. fl/serialization/, fl/motion/, fl/transitions/).

    I was taught to have a com folder at par with our main AS file and branching toward all other class dependencies with com representing the .com from the URL you got your dependency from. E.g. com/yahoo/yui/, com/adobe/serialization, etc.

    You also might want to consider denoting different versions of the adobe core lib classes if you’re not running some other kind of version control like CVS or SVN. E.g. com/adobe/core_lib.v.1/serialization or even com/adobe_v.1/.

    Again, your choice, but to others out there, please feel free to contribute your method of choice.

    Thanks,

    -A

  27. Skip Says:

    Thanks again. Being new to Flash classes I want to be as tiddy as I can. I used your classes and everything seems to be working. I can get JSON data from a few public sources. However, the conversion to array doesn’t seem to work ?

    For example: I used the following URL to check if the classes were working:

    http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO

    It returns a small JSON file. I have not stepped in the code to see where it is failing but I get the following error messages:

    TypeError: Error #1034: Type Coercion failed: cannot convert Object@14c035b1 to Array.
    at JSONTest_fla::MainTimeline/decodeJSON()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    No biggy. I will spend some time looking at it. Again, thank you.

    -Skip

  28. Andres Says:

    Hint, notice the difference between how the data in your link and that of my example is construed…. specifically, the { } vs. [ ].

  29. Skip Says:

    I see…is this typical of JSON ? To be either {} or [] ? I am new to this stuff.

  30. Skip Says:

    Andres,
    Hello again. I changed my JSON format to the following:

    [{"date": "Tue 12:35:01 PM", "text": "started", "id": "00", "event": "server notice"},
    {"date": "Tue 12:35:07 PM", "text": "checking 'client_1'", "id": "01", "event": "index notice"}]

    It looks correct to me, but I am still getting the same parse error ?

    Thanks,
    Skip

  31. Andres Says:

    Hi Skip,

    Just got back from vacation.

    So what you’re trying to do in the above comment is have an array of objects, Well it seems your JSON is valid via http://www.jsonlint.com/, have you tried having all your JSON in one line, line breaks usually cause problems.

    With regards your second to last post, basically, [x,y,z] is an array, and {x:0,y:2,z:3} is an object. Incidentally, you can’t have {x,y,z}, you always need to define each object’s property, either via…

    /*The long way of creating an object*/
    //Define the function/class, and I’ll throw in a public and private var (defined in the constructor) for some added learning.
    function Blah(){
    this.z = 2;//Public var
    var priv = 9//Private var
    }
    var blah = new Blah();//Create the object.
    blah.x = 0; //Define a property within it, which will always be public.
    blah.y = 1;

    console.log(blah.x);//Outputs 0… You need Firebug to see this. And I’d recommend having it anyway.
    console.log(blah.z);//Outputs 2
    console.log(blah.priv);//Outputs undefined because it’s private.

    /*Or the quick way (as an object literal).*/
    var blah2 = {x:0, y:1};//But all vars are public… same as having done this.z = 2, or blah.x=0, above.
    console.log(blah2.x) ;//Outputs 0

    /*For the sake of learning, here’s the long way and short way for creating an array*/
    var blah3 = new Array(0);
    blah3.push(1);
    blah3.push(2);
    console.log(blah3[0]);//Outputs 1
    console.log(blah3[1]);//Outputs 2

    //Short way…
    var blah4 = [1,2,3,4];
    console.log(blah4[0]);//Outputs 1
    console.log(blah4[1]);//Outputs 2

    And lastly, it’s good practice to quote properties within an object literal {“x”:..}, so good work.

    -A

  32. Skip Says:

    Andres,
    I just wanted to say thank you for the help. Been away for some time myself.

    Thanks again,
    Skip

  33. Skip Says:

    Of course I spoke to soon :) . I noticed that the JSON.decode() function returns Object. When I try to do the following, it fails:

    var dataArray:Array = JSON.decode(myJson);

    TypeError: Error #1034: Type Coercion failed: cannot convert Object@3886561 to Array. at JSONTest_fla::MainTimeline/decodeJSON()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    I understand the error but not how to convert the the JSON to an array of objects ?

    Thanks,
    Skip

  34. Zach Says:

    Thanks for this tutorial!

  35. Vince Says:

    My I ask why Flash 8 says “?Unexpected file format” with the example .fla file?

  36. steveR Says:

    how do you coerce the json to a class?
    ie

    two AS classes
    public class people
    {
    public var persons:Array;
    }

    public class person
    {
    public var name:String;
    public var number:String;
    }


    var p:people =new people();
    p.persons=new Array();

    var pers:person = new person();
    pers.name=”fred”;
    pers.number=”12345″;
    p.persons.push(pers);

    var ostr:String= JSON.encode(p);

    var p2:people = JSON.decode(ostr) as people;

    —————————————-
    Type Coercion failed: cannot convert Object@570a3d1 to people

  37. Newbie Says:

    I appreciate this tutorial, but have one question please:

    To what folder should I download the adobe core library in Step 2?

    i.e., what should be parent folder of “src/com/adobe/serialization/json” after using Winzip to unzip the downloaded as3corelib-92.1.zip (which I’m supposed to do, correct?) ?

    I’m using ActionScript 3.0 in Flash 10 and CS4 (and not Flex).

    Thanks for any help.

  38. Andres Says:

    I placed the src folder next to my project files (.as etc.). But it’s really up to you as long as your paths throughout the tutorial correctly point to the json folder’s location.

  39. TranquilX7 Says:

    Nice tutorial.
    also check out my tutorial on Loading in JSON file or JSON RSS feed and parsing it.

    http://tranquilx7-flashmade-ez.blogspot.com/2009/06/how-to-read-and-parse-json-files.html

    hope it helps

Leave a Reply