Andy McKay

Feb 12, 2010

Accessing JSON from Adobe Air


So you have a REST style API on a server that returns JSON that you'd like to access from Adobe Air app (using Javascript). Seems simple right? There's a few tricks in there.

Firstly cross domain. Once you've set up your URLLoader and made your request, you'll get a response back. The only problem is that you can't access the data in it. In the Air Introspector:

event.target

Will show you there's a data element and the data contains your JSON. But no matter what, you can't access it:

event.target.data

Will always return "undefined", not "You can't access this due to cross domain policy" or something useful. So go to your server and add in the following at the URL /crossdomain.xml:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

Now you've got your JSON. So you could just eval it? Fortunately Adobe blocked that, eval is nasty anyway. How about using jQuery.parseJSON? Nope:

Adobe AIR runtime security violation for JavaScript code in the application security sandbox

So I grabbed json2.js and did:

JSON.parse(event.target.data)

...and then we've got the JSON.