Highlighted

Flex and JSON

Avatar

Avatar

Stinky_Tofu

Avatar

Stinky_Tofu

Stinky_Tofu

01-09-2008

I am having some trouble getting the JSON.decode() method
working.



I currently have the following JSON file in UTF-8 format:



{"states":[{"id":140,"state":"Alabama","obama":6,"mccain":5,"ec":3},

{"id":91,"state":"Alaska","obama":4,"mccain":5,"ec":3}],

"USA":{"obama":7450, "mccain":7450}

}



I am accessing it in Flex with the following code:



<mx:Script>

private function onJSONLoad(event:ResultEvent):void

{

var rawData:String = String(event.result);

var countries:Array = (JSON.decode(rawData) as Array);



Alert.show(countries.length as String);

var dp:ArrayCollection = new ArrayCollection(arr);



voteTable.dataProvider = dp;

}

]]>

</mx:Script>



<mx:HTTPService

id="service"

resultFormat="text"

fault="faultHandler(event)"

url="
http://localhost/gec/vote.json"

result="onJSONLoad(event)"

showBusyCursor="true" />



However, for the life of me, I cannot get Flex to correctly
parse the JSON code into an array. In the line:



var countries:Array = (JSON.decode(rawData) as Array);



The countries array never gets populated with any of the data
from the JSON file, even though I the contents of the rawData
variable correctly contain all the JSON code. The countries array
always remains empty.



Help me Obi-wan, you're our only hope!! I have been working
on this problem for the past two days and have yet to figure out
what is wrong.



What am I doing wrong? Can someone point me in the right
direction? Is there a problem with the JSON code structure? Is
there something remarkably stupid I am overlooking? Hope someone
can help look at this with a fresh pair of eyes and see if they can
spot the problem, because I have really hit a wall here and don't
know what else to do but to post on the forums for help!!



Many thanks!



Phil