Tutorial : Using JSON with Flex 2 and ActionScript 3
One of the little gems you will find in the open source ActionScript 3 libraries that we released on labs, is the JSON class found in the corelib library. This class, written for Adobe by Darron Schall, makes it super simple to both serialize and de-serialize JSON data.
What is JSON you ask? From the JSON website:
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.
In a nutshell, JSON is a way to serialize data using JavaScript syntax. It is fairly compact, and easy to use. Furthermore, it has become increasingly popular due to the growth of AJAX applications, and the browser’s native support of de-serializing JSON (via eval()).
If you look on the main page of my weblog, the Reading / Doing section on the left is actually a small AJAX widget I created that shows my latests diggs, delicious bookmarks, and items added to my ta-da lists. It gets its data from a JSON feed on the server, which is periodically generated by a PHP file.
So, to show how to use JSON within a Flex / Flash application, we will load the JSON feed from my site into Flash and display it in a datagrid. Nothing earth shattering, but it will show how easy it is to use JSON. I am not assuming that you know anything about Flex / ActionScript or JSON. Because of this, the tutorial will be pretty long, as I want to make sure I cover every step of the process.
You can view the completed example here. (Requires Flash Player 8.5 beta 2).
First, you need to make sure you have the following installed:
You can grab Flex Builder and MXMLC from labs (the MXMLC compiler is included with the Flex Builder install, and also in the SDK download (in case you are on MAC or Linux).
Once you download the zip file for the corelib library, unzip it and you should see three subfolders: src, bins, docs.
- src : contains the source code for the library
- bin : contains a compiled SWC of the library (you can think of this as a DLL)
- docs : contains the API docs for the library
You can link the project against either the source, or the SWC. For this example, we will use the SWC since we don’t need to edit the source code any.
Once Flex Builder is install, open it and make sure that you are in the Flex Development perspective.
Window > Open Perspective > Flex Development
Next, make sure the navigator view is open (it is usually on the left). This view shows all of your projects and files. If the view is not open, you can open it via:
Window > Show View > Navigator
Right click in the navigator and select:
New > Flex Project
Name the Project “JSONExample” and make sure “Use default location” is checked.
Then, click the “Next” button (not finish), this takes us to a screen that will allow us to add items to our class path, or to link against libraries. (you can access this at anytime, by selecting the project, and then selecting Project > Properties).
Select the Libraries tab, and click Add SWC. Browser to the corelib.swc file which was including in the bin directory of the corelib zip file. Click the Finish button.
The first thing we need to do is to add a datagrid to display the data. Our grid will contain two columns. One for the title, and one for the type of service (delicious, digg, tada).
Make sure that the JSONExample.mxml file is open in the editor (double click it in the Navigator), and then switch to design view (click the Design button in the top left of the editor). This brings us to design view which allows us to visually layout and manipulate our components.
Once you are in design view, you should see a Components view. If not, you can open it via Window > Show View > Components. This view contains all of the built in (and any custom components) that are available to the project. Select a DataGrid component from the Controls folder and drag it onto the stage. Once on the stage, resize it so that it takes up most of the space. The grid should snap to the edges when it gets close.
Make sure the grid is selected then go to the Flex Properties view. It should be open on the right, but if it isn’t you can open it via Window > Show Views > Flex Properties. We need to do two things here:
- Give the control an ID
- Set the layout constrains
Select the Id field at the top of the Flex Properties panel, and enter “grid”. This basically gives the grid a variable name so that other controls and ActionScript can reference it.
Next, scroll all the way to the bottom of the Flex Properties view to the Layout section. This will show your component with anchor points. Make sure that the following check boxes are checked:
- Top Right
- Top Left
- Left Top
- Left Bottom
This basically tells the controls to keeps its sides the same distance from the application’s sides, even if the app / windows resizes.
At this point, we are ready to switch back to source view, and load the JSON data. So, switch back to source view (click the Source button in the top left of the editor).
You code should now look something like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute">
<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">
<mx:columns>
<mx:DataGridColumn headerText="Column 1" dataField="col1"/>
<mx:DataGridColumn headerText="Column 2" dataField="col2"/>
<mx:DataGridColumn headerText="Column 3" dataField="col3"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Lets add an HTTPService tag to actually load the data. Add the following tag right under the Application tag.
<mx:HTTPService id="service" resultFormat="text"
url="http://weblogs.macromedia.com/mesh/mashedpotato.json"
result="onJSONLoad(event)" />
If you save this, you should get an error in the problems view (Window > Show Views > Problems):
Call to a possibly undefined method 'onJSONLoad'
This is ok. We just need to define the onJSONLoad event handler. But first, lets look at the code we just wrote:
- id – Give the control a variable name so we can reference it later.
- url – the url that points to the JSON data we are loading
- resultFormat – the format that we want the data returned to us in. (In this case, just the raw text).
- result – event handler that is called when the data loads.
At this point, your code should look something like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute">
<mx:HTTPService id="service" resultFormat="text"
url="http://weblogs.macromedia.com/mesh/mashedpotato.json"
result="onJSONLoad(event)" />
<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">
<mx:columns>
<mx:DataGridColumn headerText="Column 1" dataField="col1"/>
<mx:DataGridColumn headerText="Column 2" dataField="col2"/>
<mx:DataGridColumn headerText="Column 3" dataField="col3"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Next, we need to create a script block to define our event handler function. Add a Script tag block just below the Application tag:
<mx:Script>
<![CDATA[
]]>
</mx:Script>
and then inside the Script block, lets define our event handler. You script block should now look like this:
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private function onJSONLoad(event:ResultEvent):void
{
}
]]>
</mx:Script>
If you look at the API docs, ResultEvent is the type of event broadcast when the data has loaded from the service.
Next, all we need to do is:
- Get the raw JSON data from the URL
- De-serialize it from JSON to ActionScript
- Set the data as the dataProvider for the grid
Here is the completed function, with comments:
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import com.adobe.serialization.json.JSON;
private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);
//decode the data to ActionScript using the JSON API
//in this case, the JSON data is a serialize Array of Objects.
var arr:Array = (JSON.decode(rawData) as Array);
//create a new ArrayCollection passing the de-serialized Array
//ArrayCollections work better as DataProviders, as they can
//be watched for changes.
var dp:ArrayCollection = new ArrayCollection(arr);
//pass the ArrayCollection to the DataGrid as its dataProvider.
grid.dataProvider = dp;
}
]]>
</mx:Script>
Notice that we also added some import statements to bring in the relevant classes.
The actual JSON de-serialization part is pretty trivial and consists of this one line of code:
var arr:Array = (JSON.decode(rawData) as Array);
JSON.decode returns a Object (since it doesn’t know before hand what it will be de-serializing), so we have to cast the result to an Array using the “as” operator. (can’t cast using Array() for legacy reasons).
At this point, we only have two things left to do:
- Actually tell the service to load the data.
- Customize the DataGrid to map to the data we are passing it.
Telling the service to load the data is easy. Since we want it to load the data as soon as the app loads, we can just specify in in the creationComplete event for the app (this is called once the app has been loaded and the controls laid out). (You can think of this as the same as onload in HTML / JavaScript).
We just need to add this attribute to the Application tag:
creationComplete="service.send()"
Remember that service is the id / variable name for our HTTPService control. Basically, this says when the app has loaded and initialized, tell the HTTPService control to load its data.
Finally, we need to tweak the DataGrid to show our data. In this case, we only need to tweak the columns within the DataGrid.
First, remove one of the three column tags, since we only need two.
Next, we need to add better column heading titles (through the headingText attribute), and map each column to a property in the data we loaded. If you look at the JSON data, you can see the following fields in each item:
- title
- src
- url
- date
For this example, we will just show the source and title. We specify this for each column through the dataField property. So, the new columns should look like this:
<mx:DataGridColumn headerText="Service" dataField="src"/>
<mx:DataGridColumn headerText="Title" dataField="title"/>
Basically, this tells the first column to use Service as the column title, and get its data from the “src” property of the loaded data. The second column gets it data from the title property.
The completed code should now look like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute"
creationComplete="service.send()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import com.adobe.serialization.json.JSON;
private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);
//decode the data to ActionScript using the JSON API
//in this case, the JSON data is a serialize Array of Objects.
var arr:Array = (JSON.decode(rawData) as Array);
//create a new ArrayCollection passing the de-serialized Array
//ArrayCollections work better as DataProviders, as they can
//be watched for changes.
var dp:ArrayCollection = new ArrayCollection(arr);
//pass the ArrayCollection to the DataGrid as its dataProvider.
grid.dataProvider = dp;
}
]]>
</mx:Script>
<mx:HTTPService id="service" resultFormat="text"
url="http://weblogs.macromedia.com/mesh/mashedpotato.json"
result="onJSONLoad(event)" />
<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">
<mx:columns>
<mx:DataGridColumn headerText="Service" dataField="src"/>
<mx:DataGridColumn headerText="Title" dataField="title"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
If you debug / run your app, you should see a datagrid that contains all of the data from the JSON feed. (You can debug by clicking the little Bug icon on the toolbar, or selecting Run > Debug).
If you are feeling generous, you can also easily publish your source code. Go back to Flex Builder, and select the JSONExample. Then select Project > Publish Application Source. Once you do this, re-run your application, and then right click on it and select View Source.
This is a pretty simple example, but it shows how easy de-serializing JSON in ActionScript is (serialization is just as easy).
Updated : You can also view a screencast of this tutorial.
Here are the links for the resources used in the tutorial:
I will update the post with images a little later, and am considering doing a screencast of building the example.
If you liked the tutorial, make sure to digg it.
Post any questions, suggestions and / or corrections in the comments.


Great tutorial Mike. I like that you took the time to explain every detail…makes it much easier for someone new to Flex (ie. me) to find my way around and figure out what’s going on.
Rick
28 Mar 06 at 2:41 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
It is very usefull.
zikey
29 Mar 06 at 5:25 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Very good Mike. I totally agree with Rick, having every step explained is a great help. More of it please, we’re all hungry for Flex2.
Stefan Richter
31 Mar 06 at 1:12 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Mike,
this is very nice attempt. I do have one question, is there a good way to do nested data structures and get a corresponding object. Something like.
{‘EMPL’:{‘ID’:1005,’Login_ID’:'galileo’,'Name’:'Galileo Galilei’}}
{‘BOSS’:{‘ID’:1005,’Login_ID’:'galileo’,'Name’:'Hudini Galilei’}}
I would like to get a a JSON object which may have multiple arrays in it.
Thanks in advance!
Nilu.
P.S. We are *very* interested to get this Flex2 when ready. Can’t wait.
Nilu
1 Apr 06 at 7:05 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi Mike,
the new versions fo your libraries do not contain the swc files or the bin directory (as stated). Is this intentional?
Anonymous
13 May 06 at 3:06 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
>the new versions fo your libraries do not contain the swc files or the bin directory (as stated). Is this intentional?
Oops. Sorry about that. I just uploaded an fixed version of corelib that includes the swc, and will fix the rest later today.
Sorry about the hassle.
mike chambers
mesh@adobe.com
mike chambers
13 May 06 at 8:44 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Thanks for this great tute. This is exactly the kind of thing needed to walk people through Flex Builder’s workflow and showcase its features.
Mike Britton
7 Jun 06 at 11:08 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
If you use this with FlexBuilder 2, you’ll need to change com.macromedia.serialization.* to com.adobe.serialization.*
Troy Gardner
5 Jul 06 at 12:30 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
mike great tutorial, so many thanks.
Q: could you give a brief overview of how you create the JCON file using PHP? i mean is it a simple act of calling something like JCON.encode(phpObject)? i take it the php object needs to represent the DataProvider class? THANKS AGAIN!!! STEF
stef
12 Jul 06 at 7:51 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Mike, thanks for the posting on the webapis.
I’m trying to work with the flickr api, and can’t seem to get past the sandbox security. Flickr has a wildcard crossdomain.xml Loading that doesn’t seem to work when viewing as localhost or on a server.
Can you take a brief moment to give us an example of how to set up a flex app to allow flickr images to display?
It looks like a lot of effort went into the webapis, so I think it would be beneficial to all, considering there’s no tutorial on the flickr api.
Dan
30 Oct 06 at 11:55 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Thanks a lot for the example. Give us more lease.
One note for cut and pasters like me, the
import com.macromedia….
should now be
import com.adobe…
ian morton
14 Nov 06 at 11:12 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I tried out the library. One thing i found was that
the json decoder does not seem handle new lines and single quotes in json text.
I would also like to know if it there is something
like
like they have for xml so that i could bind form elements to json. I can’t seem to find it.
infimate
4 Dec 06 at 10:51 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I’m very interested in Flex2 and would’ve liked to check your example, but the example ain’t working. (I’ve the latest Flash Player on my machine).
http://weblogs.macromedia.com/mesh/files/flex/jsonexample/
The screen in empty!
Alphonso
20 Dec 06 at 7:35 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi Mike,
A great tutorial. Something needs to be corrected though.
import com.macromedia.serialization.json.JSON;
needs to be:
import com.adobe.serialization.json.JSON;
Keep up the good work.
Ahmed T.
27 May 07 at 3:42 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I don’t want to wait till the end of Summer :( , I want it now. Who with me?
save your time and join me. ;)
BustyBoots
31 May 07 at 12:54 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi,
Can you please tell me where i have to store the corelib folder.When i am going to store the file into project folder and iporting the file into library a problem occured. it says” corelib was not loaded successfully”. Please help me. I want to know more how to integrate JSON in flex.
Thanks
kalyan
1 Jun 07 at 1:25 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Once agin when i am going to see your example it is not loaded succesfully.It show some actionscript error.
the error is like this:
” VerifyError: Error #1014: Class flash.util::Timer could not be found.
at mx.managers::SystemManager/initialize()
at mx.managers::SystemManager/::initHandler()”
plese help me
Thanks and waiting for your great reply………..
kalyan
1 Jun 07 at 1:28 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
hey mike..
i tried ur example out..then i made another one with the http service url changed..can we give the target url of http service a jsp page? (because the json data to be generated depends on user input from flex) i tried making json object in the jsp page..but i guess theres sme prob with that cause the actionscript is getting stuck at the JSON.decode part..should i set any header or anything of that sort for the actionscript to recogonize the output of jsp as json? pelase clarify
ps..the ‘rawdata’ that i’m geting as string displays in the correct json format with my needed data. only at the decode part , somethings happening i guess
flexcoder
7 Jun 07 at 9:51 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Yeah, doesn’t work for me either under Flash Player 9. All I get is:
VerifyError: Error #1014: Class flash.util::Timer could not be found.
at mx.managers::SystemManager/initialize()
at mx.managers::SystemManager/::initHandler()
Interesting tutorial though, thanks!
Stephan
26 Jun 07 at 8:18 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
OK. I just checked this code, and the only change I had to make was to change:
import com.macromedia.serialization.json.JSON;
to
import com.adobe.serialization.json.JSON;
This was tested using the Flex 3 Beta:
http://labs.adobe.com/technologies/flex/
The linked example wont work, because it was compiled for a Flash Player beta, that has since changed. I have removed that link.
However, if you copy and paste the code and compile it, it will work fine.
Sorry about the confusion.
mike chambers
mesh@adobe.com
mikechambers
26 Jun 07 at 8:50 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
What about nested objects inside the JSON object. How is it possible to access them through the DataField in a Datagrid object. There is also another question before this, but there is no answer to that. Thanks, great Tutorial
evang
26 Jul 07 at 7:45 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
This is great! but… It would really help if you could show how to do something similar using an XML input, where the xml tree could define the UI tree, perhaps by specifying the number of nodes that could collapse.
Does that exist somewhere, I’m just too new to beta 3 to know where to look?
Fred
26 Jul 07 at 8:04 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Mike,
Thanks for the great example, got me on my way to doing some AIR / Flex stuff!
TigeRyan
8 Sep 07 at 6:39 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Someone asked earlier about how to do nested structures and after beating my head against a way for a while I figured I would post this…There might be another way, but this worked out for me. What I was returned via JSON was a verity recordset so it was pretty complex.
var keyArray:Array = results.DATA.KEY as Array;
var titleArray:Array = results.DATA.CUSTOM3 as Array;
var resultsCol:ArrayCollection = new ArrayCollection();
dgResults.dataProvider = resultsCol;
for(var x:int=0;x
TigeRyan
9 Sep 07 at 7:24 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Response to JSON: nested data. I will use your example and add a few things to it so that you know what you should do.
We’ll start with your example above:
{“EMPL”:{“ID”:1005,”Login_ID”:”galileo”,”Name”:”Galileo Galilei”}}
{“BOSS”:{“ID”:1005,”Login_ID”:”galileo”,”Name”:”Hudini Galilei”}}
OK, now, since Employees can be bosses and they themselves have bosses. Why don’t we look at this from the perspective of a relational database? First off, we’ll change your EMPL to an array of employees:
{
“EMPL”:[
{
"ID":1005,
"Login_ID":"galileo",
"Name":"Galileo Galilei",
"Bosses":[1006, 1007]
},
{
“ID”:1006,
“Login_ID”:”copernicus”,
“Name”:”Hudini Galilei”,
“Bosses”:[1007]
},
{
“ID”:1007,
“Login_ID”:”newton”,
“Name”:”Benjamin Franklin”,
“Bosses”:[]
}
]
}
OK. So, what do we have here? We have 3 employees, each an object in an array called EMPL. Each employee has another array called Bosses that lists the bosses for each of the employees. The numbers indicate the ID of each of the employees who act as a boss to the others.
If you think about it in the relational database way, each of the employees is a row with Bosses being a relation between the employees table and itself. Anyway, you should know that structure, it’s your project :)
I hope that helps you out. Keep in mind that each and every : pair can have a value that is an object, an array, or an atomic value.
Curt Woodard
16 Oct 07 at 8:52 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Curt,
That was real helpful.
But what about this situation where our Native AS object looks like this…
Alert.show(ObjectUtil.toString(JSON.decode(rsData)));
(Object)#0
COLUMNS = (Array)#1
[0] “COUNTRY_ID”
[1] “STATE_ID”
[2] “COUNTRY_NAME”
[3] “STATE_NAME”
[4] “COUNTRY_DEFAULT_COUNTRY_ID”
DATA = (Array)#2
[0] (Array)#3
[0] 1
[1] 1
[2] “United States”
[3] “Alabama”
[4] 1
[1] (Array)#4
[0] 1
[1] 2
[2] “United States”
[3] “Alaska”
[4] 1
[2] (Array)#5
[0] 1
[1] 3
[2] “United States”
[3] “Arizona”
[4] 1
I’d like to combine these 2 objects and return a single ArrayCollection.
Curt
12 Dec 07 at 8:16 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
great work… but i think i ran into trouble,
import com.macromedia.serialization.json.JSON;
import com.adobe.serialization.json.JSON;
does not exist?! i am using Adobe Flex Builder 2. any idea?
bluejay
11 Jan 08 at 9:00 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi Mike,
This tutorial is a great start for all beginners like me. I have a query. I am trying to get rows from a table of a oracle database from which i have to create json objects from this data and then display them in my flex grid.
I dont know the exact implementation of this. I can access data using java. But how does json gets this data as string or array.
On the whole , if you can explain me the flow that would be a million for me.
Thanks for the help in advance
Stranger
stranger
16 Jan 08 at 12:55 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi Mike,
I have the dwr file that returns the json objects. But how can i execute that DWR from flex and retrieve the json data.
Thanks for the help
Keshav.
stranger
17 Jan 08 at 9:15 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I got this error when try to view your example:
VerifyError: Error #1014: Class flash.util::Timer could not be found.
at mx.managers::SystemManager/initialize()
at mx.managers::SystemManager/::initHandler()
Jason
23 Jan 08 at 10:06 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
NESTED Structures:
Ok. I’m not entirely sure the nested structure question has been answered. Here is another:
Suppose you have a json file with an ARBITRARY nested structure (unknown in advance, please do not ask why). A true de-serializing library should automatically reconstruct the data model from the file. Will the json library do this? Can it construct a nested associative array with the keys extracted from the json file?
sal
2 Feb 08 at 7:53 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Thanks for the tutorial, it was very helpful!
Jared
18 Feb 08 at 11:27 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Good tutorial.
One question for you:
Is there anyway to feed data using JSON string instead of JSON file from the server?
Ying
29 Feb 08 at 1:40 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
@”Curt” above about the array collection:
var myArrayCollection =
{
“COLUMNS” :
[
"COUNTRY_ID", "STATE_ID", "COUNTRY_NAME", "STATE_NAME", "COUNTRY_DEFAULT_COUNTRY_ID"
],
“DATA” :
[
[1, 1, "United States", "Alabama", 1],
[1, 2, "United States", "Alaska", 1],
[1, 3, "United States", "Arizona", 1]
]
};
There is your JSON object. You could easily structure it thusly:
var myArrayCollection2 =
{
“Alabama” : {
“COUNTRY_ID” : 1,
“STATE_ID” : 1,
“COUNTRY_NAME” : “United States”,
“STATE_NAME” : “Alabama”,
“COUNTRY_DEFAULT_COUNTRY_ID” : 1
},
“Alaska” : {
“COUNTRY_ID” : 1,
“STATE_ID” : 2,
“COUNTRY_NAME” : “United States”,
“STATE_NAME” : “Alaska”,
“COUNTRY_DEFAULT_COUNTRY_ID” : 1
},
“Arizona” : {
“COUNTRY_ID” : 1,
“STATE_ID” : 3,
“COUNTRY_NAME” : “United States”,
“STATE_NAME” : “Arizona”,
“COUNTRY_DEFAULT_COUNTRY_ID” : 1
}
};
The second is quite a bit more verbose, but you could access it like this:
var MyVar = myArrayCollection.Alaska.COUNTRY_ID;
The previous is a little more cryptic:
var MyVar = myArrayCollection.DATA[0][0];
There are different ways to do it.
Sorry about taking so long to notice that you replied to my message…
-Curt
Curt Woodard
29 Feb 08 at 4:09 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Thank you for the Tutorial, but the URL “http://weblogs.macromedia.com/mesh/mashedpotato.json” ist cease to exist. Could you fix it?
kiki
21 Mar 08 at 2:52 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi Mike,
Does the corelib 90 and/or 85 work with Flex3?
I followed your instructions, creating a new project JSONExample. Created the mxml file based on the source provided in this instruction.
I have added the corelib swc file/path to the project build path. What could be the problem?
======================================================
Error: Unexpected < encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()[C:\Documents and Settings\mchamber\My Documents\src\flashplatform\projects\corelib\trunk\src\actionscript3\com\adobe\serialization\json\JSONTokenizer.as:492]
at com.adobe.serialization.json::JSONTokenizer/getNextToken()[C:\Documents and Settings\mchamber\My Documents\src\flashplatform\projects\corelib\trunk\src\actionscript3\com\adobe\serialization\json\JSONTokenizer.as:171]
at com.adobe.serialization.json::JSONDecoder/nextToken()[C:\Documents and Settings\mchamber\My Documents\src\flashplatform\projects\corelib\trunk\src\actionscript3\com\adobe\serialization\json\JSONDecoder.as:88]
at com.adobe.serialization.json::JSONDecoder()[C:\Documents and Settings\mchamber\My Documents\src\flashplatform\projects\corelib\trunk\src\actionscript3\com\adobe\serialization\json\JSONDecoder.as:63]
at com.adobe.serialization.json::JSON$/decode()[C:\Documents and Settings\mchamber\My Documents\src\flashplatform\projects\corelib\trunk\src\actionscript3\com\adobe\serialization\json\JSON.as:81]
at JSONExample/onJSONLoad()[C:\Documents and Settings\Administrator\My Documents\Flex Builder 3\JSONExample\src\JSONExample.mxml:51]
at JSONExample/__service_result()[C:\Documents and Settings\Administrator\My Documents\Flex Builder 3\JSONExample\src\JSONExample.mxml:65]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.rpc.http.mxml::HTTPService/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\http\mxml\HTTPService.as:275]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:191]
at mx.rpc::Responder/result()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\Responder.as:41]
at mx.rpc::AsyncRequest/acknowledge()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:74]
at DirectHTTPMessageResponder/completeHandler()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\messaging\channels\DirectHTTPChannel.as:381]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
Alex
27 Mar 08 at 2:13 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I too am having a difficult time getting the JSON string to decode. Here is the JSON feed I am testing against:
http://www.flickr.com/services/feeds/photos_public.gne?tags=flex&format=json
Error: Unexpected j encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()[C:\\corelib\src\com\adobe\serialization\json\JSONTokenizer.as:546]
I think that might have something to do with the structure of the Flickr JSON feeds, but I am a little in the dark on what a feed should look like. I would be great to see your sample feed working again.
Thanks :)
Jason
16 Apr 08 at 11:28 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
LOL, you know how it is … as soon as you post asking for help you figure it out. Here is the solution for the Flickr JSON feed
private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);
// Rip off the Flickr header
rawData = rawData.split(“jsonFlickrFeed(“).join(“”);
//decode the data to ActionScript using the JSON API
var obj:Object = JSON.decode(rawData);
// Access the items node to get the array of items
var arr:Array = (obj.items as Array);
//create a new ArrayCollection passing the de-serialized Array
//ArrayCollections work better as DataProviders, as they can
//be watched for changes.
var dp:ArrayCollection = new ArrayCollection(arr);
//pass the ArrayCollection to the DataGrid as its dataProvider.
grid.dataProvider = dp;
}
Jason
16 Apr 08 at 11:47 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hello, when i save the json string(Object -> String) in one database, and i`m trying to get the object (String -> Object), but have and error :
the String = [{"cargo":"teste","tipo":"Químico","epis":"[{"eficaz":"Sim","caepi":"7676","gfip":"76"},{"eficaz":"Sim","caepi":"76763","gfip":"763"}]“,”intensidade”:”67587″,”empresa”:”kmmedicina”,”tecnica”:”68756897″,”fatorderisco”:”7698rg”}]
my code:
var objAt:Object = (re[i] as Object);
trace(objAt)
var id:int = int(objAt.id);
var str:String = String(objAt.riscos);
trace(“STR: “,str);
var tobj:Array = (JSON.decode(str) as Array);
and the error:
Error: Unexpected e encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()[C:\Actionscript\com\adobe\serialization\json\JSONTokenizer.as:546]
at com.adobe.serialization.json::JSONTokenizer/getNextToken()[C:\Actionscript\com\adobe\serialization\json\JSONTokenizer.as:171]
at com.adobe.serialization.json::JSONDecoder/nextToken()[C:\Actionscript\com\adobe\serialization\json\JSONDecoder.as:86]
at com.adobe.serialization.json::JSONDecoder/parseObject()[C:\Actionscript\com\adobe\serialization\json\JSONDecoder.as:169]
at com.adobe.serialization.json::JSONDecoder/parseValue()[C:\Actionscript\com\adobe\serialization\json\JSONDecoder.as:199]
at com.adobe.serialization.json::JSONDecoder/parseArray()[C:\Actionscript\com\adobe\serialization\json\JSONDecoder.as:111]
at com.adobe.serialization.json::JSONDecoder/parseValue()[C:\Actionscript\com\adobe\serialization\json\JSONDecoder.as:202]
at com.adobe.serialization.json::JSONDecoder()[C:\Actionscript\com\adobe\serialization\json\JSONDecoder.as:64]
at com.adobe.serialization.json::JSON$/decode()[C:\Actionscript\com\adobe\serialization\json\JSON.as:81]
at Janelas.Riscos::CadastrarRiscos/recebeTodos()[C:\Users\adm\Documents\Flex Builder 3\Teste KM\src\Janelas\Riscos\CadastrarRiscos.mxml:216]
do you have any idea, of what is this ?
thank you.
Armando Leopoldo Keller
6 May 08 at 11:05 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I followed the instructions, even pasted in the code (after notepading it to make sure it’s plain text) and still get the following error … ideas?:
Error: Unexpected < encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONTokenizer.as:546]
at com.adobe.serialization.json::JSONTokenizer/getNextToken()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONTokenizer.as:171]
at com.adobe.serialization.json::JSONDecoder/nextToken()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONDecoder.as:86]
at com.adobe.serialization.json::JSONDecoder()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONDecoder.as:63]
at com.adobe.serialization.json::JSON$/decode()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSON.as:81]
at main/onJSONLoad()[C:\Documents and Settings\Cactusware\My Documents\dspro\JSON Example\src\main.mxml:18]
at main/__service_result()[C:\Documents and Settings\Cactusware\My Documents\dspro\JSON Example\src\main.mxml:32]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.rpc.http.mxml::HTTPService/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\http\mxml\HTTPService.as:275]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:191]
at mx.rpc::Responder/result()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\Responder.as:41]
at mx.rpc::AsyncRequest/acknowledge()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:74]
at DirectHTTPMessageResponder/completeHandler()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\messaging\channels\DirectHTTPChannel.as:381]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
John Hall
13 May 08 at 12:15 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
http://weblogs.macromedia.com/mesh/mashedpotato.json seems to be missing, although my application runs fine…
Thanks
Keith
20 May 08 at 9:55 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I’m having the same issue as John Hall. It seems to be an issue with Flex 3 and the corelib ActionScript 3 library.
Anyone found a solution to this?
Bill
2 Jun 08 at 12:48 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi Mike,
I am getting the following error when tried to use the code provided in this blog. I appreciate any help is provided to me to sort out this issue.
Error: Unexpected o encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONTokenizer.as:546]
at com.adobe.serialization.json::JSONTokenizer/getNextToken()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONTokenizer.as:171]
at com.adobe.serialization.json::JSONDecoder/nextToken()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONDecoder.as:86]
at com.adobe.serialization.json::JSONDecoder/parseObject()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONDecoder.as:142]
at com.adobe.serialization.json::JSONDecoder/parseValue()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONDecoder.as:199]
at com.adobe.serialization.json::JSONDecoder()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSONDecoder.as:64]
at com.adobe.serialization.json::JSON$/decode()[C:\Development\ContractProjects\Adobe\as3corelib\src\com\adobe\serialization\json\JSON.as:81]
at TestJSON/onJSONLoad()[D:\Other\Workplace\Flex\SampleProject\src\TestJSON.mxml:15]
at TestJSON/__xmlRpc_result()[D:\Other\Workplace\Flex\SampleProject\src\TestJSON.mxml:34]
at flash.events::EventDispatcher/dispatchEventFunction()
Awaiting for your reply.
Thanks for your precious time.
Sreekanth S
Sreeks
10 Jun 08 at 2:57 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
how remove the error “call to possibly undefined method JSONDecoder”
i import all the classes like
import com.adobe.serialization.json.JSONDecoder;
but in that after typing import.com.adobe. ,i get only sourceview,does not get serialization in that how to get that…i am flex beginner…if u helping means its a great thing…….
anoop
25 Jun 08 at 8:39 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I have a Flex / JSON / DWR issue :
private function onJSONLoad(event:ResultEvent):void
{
var params:Object = {};
params["callCount"] = “1″;
params["page"] = “/index.jsp”;
params["c0-scriptName"] = “Suggest”;
params["c0-methodName"] = “search”;
params["c0-id"] = “0″;
params["c0-param0"] = “string:search-term”;
params["c0-param1"] = “string:goodman group%7C”;
params["c0-param2"] = “number:10″;
params["batchId"] = “0″;
params["scriptSessionId"] = “Nathan-DeskTop”;
trace(params);
trace(“service call begin”);
service.send(params);
trace(“service call end”);
}
The above Action script POSTs data to a Servlet below well :
It fails to post data to a JSON/DWR based service below :
The response from the DWR service is below :
//#DWR-REPLY
if (window.dwr) dwr.engine._remoteHandleBatchException({ name:’org.directwebremoting.extend.ServerException’, message:’The specified call count is not a number: null’ });
else if (window.parent.dwr) window.parent.dwr.engine._remoteHandleBatchException({ name:’org.directwebremoting.extend.ServerException’, message:’The specified call count is not a number: null’ });
Based on the error ‘The specified call count is not a number: null’ – I guess the params["callCount"] = “1″; is not posted to the server. Probably nothing gets posted to the server in the JSON format.
I tried these below, no luck
//service.send( JSON.encode(params) );
//var encoder:JSONEncoder = new JSONEncoder(params);
//service.send( encoder.getString() );
Wondering how to post JSON data, could you please help ?
Nathan Pillai
8 Jul 08 at 2:22 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Same problem as anoop
Jesse Donat
28 Aug 08 at 10:43 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Can Someone paste the json file, cause I have a feeling it’s not being found.
Joseph Zibara
9 Oct 08 at 11:46 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
define variables:
[Bindable]
public var texto:String;
[Bindable]
public var teste:ArrayCollection = new ArrayCollection([{"title":"Matthews","src":"Matt"},{"title":"Matthews2","src":"Matt2"}]);
define function to encode:
public function JSONfunc(entrada:Object):void
{
var arr1:Array = new Array(entrada);
var arr3:ArrayCollection = new ArrayCollection(arr1);
var js:JSONEncoder = new SONEncoder(arr3[0].source);
texto = JSONEncoder(js).getString();
}
call function:
Robalinho
21 Nov 08 at 5:59 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Can anyone let me know how I can send JSONObject or JSONArray using Flex HTTPService?
Also can anyone shed light on how to receive the same as JSONObject or JSONArray in Java.
I am trying something like this in Java
@Path(“/datareceive”)
public class DataReceive {
@PUT
@Consumes(“application/json”)
public String putProduct(JSONObject jsonEntity) throws JSONException {
System.out.println(jsonEntity.length());
return “”;
}
}
The following is the error that I get when I try to send JSON Encoded data from Flex using HTTPService
Error #1065: Variable {“id”:”userCollection”,”users”:[{"name":"user0","password":"password0","login":true,"flags":[1,2,3,4,5,6],”role”:{“name”:”user”}},{“name”:”user1″,”password”:”password1″,”login”:false,”flags”:[1,2,3,4,5,6],”role”:{“name”:”user”}}],”userCount”:2,”extension”:null,”flags”:["a","b","c",false,1,5,77,null]} is not defined.
What could be the reason behind the issue?
Thanks
Krishnan
Krishnan
28 Nov 08 at 2:42 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I’m coming to the source as I can’t find an answer anywhere else. How do I get nested array field’s into a dataGrid column? Currently I have:
private function sentimentRH(event:ResultEvent):void {
var data:Object = JSON.decode(event.result.toString())
myArray = new ArrayCollection(data.features);
}
The top level array is features, the nested array is products. dataField=”name” gives me features.name however I’m unable to get product.* into a column.
The dataGrid dataField is fine pulling fields out of the top level array but doesn’t understand features.product. Searching around I’ve found some clues to using labelFunction rather than dataField but I can’t find any detailed explanation of implementing it although I understand it to be “complex”… I’m fairly new to Flex/AS and totally stuck, any explanation/example would be much appreciated. There is one response above that makes sense but is apparently cutoff(?).
TIA/
Brian
9 Jan 09 at 12:49 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Brian,
I just happened to come across this post and your comment.
I’m also a beginner in Flex. :-)
I found this post by Alex Harui from Adobe’s Flex team, I think it will be very helpful:
http://blogs.adobe.com/aharui/2007/03/thinking_about_item_renderers_1.html
The Sub-Object Item Renderer may be close to what you’re looking for. So check it out and hopefully you can find your answer.
As for label function, maybe this can help:
http://blog.flexexamples.com/2007/09/25/creating-a-simple-label-function-on-a-flex-combobox-control/
Anh Quy
Anh Quy
18 Feb 09 at 8:53 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
very good tutorial,,nice , helped me a lot…
Thank u very much………
Srinivas
20 Apr 10 at 3:03 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I got same error as anoop and Jesse Donat, “call to possibly undefined method JSONDecoder”. The reason I got it, was that my project wasn’t properly set up. The project location was at the project root, instead of \flex-client.
tutaren
22 Apr 10 at 6:05 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Thank you very much! As I don’t like XML, JSON rulez!
Herberth Amaral
10 May 10 at 4:22 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I’m a beginner in Flex and your tutorial would have been very helpful; if there weren’t too many dead links. I would assume the rest are pretty helpful but without examples and with links that take me nowhere, it’s just frustrating. So I’m giving on you.
Thanks for posting. I hope you find the time to take care of the links.
Cheers.
Q
10 Jul 10 at 11:49 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hey, good tutorial. I tested my application locally (calling an external json file) and works fine.
But when I upload the application to my server (different server than the Json file), doesn’t work.
Any tip ?
Thanks
Mauricio
11 Jul 10 at 9:16 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Does anyone have a current link whence to download the JSON library compatibly with the Flex 3.5 SDK? TIA
Kingpin
6 Feb 11 at 8:53 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hi,
I have imported swc (.93) in CS5. I imported the package.
I get the following error:
eferenceError: Error #1065: Variable com.adobe.serialization.json::JSON is not defined.
any suggestion?
Cesare
31 Mar 11 at 6:39 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
links are broken
fox
20 Apr 11 at 8:52 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Mike,
Now that Adobe owns MM, do you have any idea where they stuck the sample json file??? I tried finding it on the Adobe site, but did not have any luck.
Tony
Anthony Jackman
24 May 11 at 12:36 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
Hey, as other people have said, the links doesn’t work properly anymore. Being new to this I’m just trying stuff, so I figured I just used another JSON link containing some text. So, I changed the url: http://weblogs.macromedia.com/mesh/mashedpotato.json to:
http://itpdp.iriscouch.com/mad/Agurk, which is just showing the following:
{“_id”:”Agurk”,”_rev”:”1-92edd51957aa02c40c9df0200f278385″,”Energi”:10,”Kulhydrat”:3,”Kostfibre”:2,”Kategori”:”Frugt”}
So i guess that instead of src and title in the dataField, i need to write some of the fields from my own JSON link, like “Kategori” or “Frugt”, right? Well, it doesn’t work, so I must be doing something wrong :P Hope someone can help :)
LeanNax
LeanNax
15 May 12 at 10:58 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>