Aliaspooryorik
ColdFusion ORM Book

JSON String to object in Flex

I'm storing JSON strings representing complex data in my database. I then get the JSON (along with the other database row data) via a ColdFusion query and a RemoteObject call in my Flex application. The trouble I had was that Flex just treats the JSON string as, well a string! What I needed to be able to do was get Flex to evaluate the JSON string and convert it into an object.

My JSON string looks something like this:


{"name":"John Whish","nickname":"Aliaspooryorik","languages":["cfml","html"],"address":{"county":"Devon","country":"UK"}}

The solution is incredibly simple (when you know how!). All you need to do (for Flex Builder 3) is:

  1. download the as3corelib package from http://code.google.com/p/as3corelib/
  2. extract the files somewhere
  3. in flex builder, open up your project properties
  4. select the "Flex Build Path" section
  5. select the "library Path" tab
  6. click the "Add SWC" button
  7. browse to the as3corelib.swc file that you extracted above
  8. click "OK"

Now in your code you can do something like:


import com.adobe.serialization.json.JSON;

private function remoteObjectCallResult( e:ResultEvent ):void
{
// I handle the result from a call to Coldfusion which returns a single row as a Query object
var recordset:ArrayCollection = e.result as ArrayCollection;

// get the first row from the query and convert to an object
var row:Object = recordset.getItemAt( 1 );

// get the query column that holds the JSON data and convert to an object
  var jsonAsObject:Object = JSON.decode( row.json_data );

  // output data to the console
  for (var keyname:String in jsonAsObject)
  {
  trace ( keyname + ": " + jsonAsObject[ keyname ] );
  }
}

I am a Flex newbie, so this code can probably be improved but I hope it gives someone else a head start!


2 comments

  1. Hi, i have successfully installed FB 4.6 and I'm getting compilation errors ---
    Can not resolve a multiname reference unambiguously. JSON (from /Applications/Adobe Flash Builder 4.6/sdks/4.6.0/frameworks/libs/air/airglobal.swc(JSON, Walker)) and com.adobe.serialization.json:JSON don't know how to solve this. Can any one help me?

    Thanks,
    Raja.

    Comment by raja – December 14, 2011
  2. Same Error here !! help please !!!

    Comment by RajaRam – December 17, 2011

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments
 

Search

Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)

Categories

Recent Posts