Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and parse JSON in Actionscript

What I want to do is make a get request to this URL: http://api.beatport.com/catalog/3/most-popular, which should return some JSON and then parse out certain information from it.

How would I go about doing this in Actionscript 3? I'm more concerned with figuring out how to get the data to feed to a JSON parser rather than parsing the JSON, since there seem to be plenty of questions about parsing JSON. The reason I want to do this in AS3 is that I have a 3D flash visualization set up and I want to get this data, parse out the relevant bits, and then display the parsed bits in the visualization.

I'm open to any other ways of doing this that can easily be integrated with Flash besides AS3 if there's an easier way to do it in another language.

like image 657
Saliceran Avatar asked Apr 11 '12 17:04

Saliceran


2 Answers

  1. Add the corelib.swc to your library path.

  2. Import the JSON library: import com.adobe.serialization.json.JSON;

  3. Call your service with code something like this:

    var request:URLRequest=new URLRequest();
    request.url=YOUR_ENDPOINT
    request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
    request.method=URLRequestMethod.GET;
    var loader:URLLoader=new URLLoader();
    loader.addEventListener(Event.COMPLETE, receive);
    loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, notAllowed);
    loader.addEventListener(IOErrorEvent.IO_ERROR, notFound);
    loader.load(request);
    
    protected function receive(event:Event):void
    {
         var myResults:Array=JSON.decode(event.target.data);
    }
    
  4. Parse the results with JSON.decode(results).

as3corelib is maintained here: https://github.com/mikechambers/as3corelib#readme.

like image 132
Matt Garland Avatar answered Oct 13 '22 00:10

Matt Garland


Alternatively if you're using Flash Player 11 or AIR 3.0 or higher you can use the built in JSON object to decode your JSON. It's a top level object so you dont even need to import anything, just do:

var decoded : Object = JSON.parse(loadedText);

See: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html

like image 29
plemarquand Avatar answered Oct 13 '22 01:10

plemarquand