Working with JSON - Making Flex and PHP talk - Painlessly
While working on a project; designing a RIA in Adobe Flex, I was using the a Data Grid, and populating it using a HTTP Service that ran PHP.
It was a painful process.
- Check the validity of the request
- Query the database.
- Store the returned data into a usable format.
- Manually encode it into XML using for each loops (Sometimes multiple for loops).
- Then echoing that data back to Flex.
Some of the stuff that had to be done was mandatory... but I was making one task on that list more painful than it should have been.
I was manually encoding the data into XML. This took painfully long and was very annoying to deubg. Thankfully, a friend told me about JSON.
Another hidden gem in the programming world. (Maybe it's not to hidden - I just didn't know about it).
Json - pronounced Jason - Javascript Object Notation.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
Source: json.org
That pretty much sums up what makes JSON so perfect. You only need to read the first paragraph on the website to understand what makes it so easy to use.
'Installing' JSON to work with Flex and PHP
You will need to download the ActionScrpit 3 Core Libaray.
You will also need to enable the JSON extension for PHP. (For PHP 5.2.0 and onwards, the extension is compiled and enabled by default).
If you still need help installing an extension, refer to my other posts here and here. If you need further help, leave a comment, and I'll do my best to answer.
Since JSON is enabled as an extension, there is nothing else you need to do start using it. Just called json_encode or json_decode whenever you need it.
With the ActionScript 3 Core Libarary that you just downloaded, copy the 'json' folder to your Flex installation directory. I put mine under "Program Files\Adobe\Flex Builder 3\sdks\3.0.0".
Fire up Flex Builder and create a new Project. When you are prompted to Set Build Paths, click on the Libary Path tab. Select Add SWC. Navigate to where you coppied the JSON folder. Then navigate a little further and select "\json\corelib\bin\corelib.swc".
You have just enabled JSON on both Flex and PHP and are now ready to use them.
I will write up an example that shows how to use these too effectively.


