19 Replies Latest reply on Jul 13, 2011 1:55 PM by li0uid

    Populating JSON Data to Combobox - Need Help!

    li0uid

      Hello,

       

      I am trying to use a dynamicly created JSON comming from a webservice to populate comboboxes. I am really new to Flex and ActionScript 3.0.

      The problem what i have here is that my combobox stays empty. I am trying to fill it with all values from "key" (representing the manufacturers)

       

      Here´s my Code so far:

       

      [CODE]<?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute"
                      creationComplete="service.send(params)" xmlns:s="library://ns.adobe.com/flex/spark">
          <mx:Script>
              <![CDATA[
                  import com.adobe.serialization.json.JSON;
                 
                  import mx.collections.ArrayCollection;
                  import mx.rpc.events.ResultEvent;
                 
                  public var myURL:String = "http://dev.ws.topdata.de/data/tdifdata.php?";
                  public var params:Object = {Lookup: "DeviceManufacturerId"};
                 
                  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 Combobox as its dataProvider.
                      dropdown.dataProvider = dp;
                     
                      trace(rawData);
                  }
              ]]>
          </mx:Script>
         
          <mx:HTTPService id="service" method="GET" resultFormat="text" url="{myURL}" result="onJSONLoad(event)">
             
          </mx:HTTPService>
         
          <s:ComboBox x="26" y="33" labelField="key" id="dropdown"/>   
         
      </mx:Application>[/CODE]

       


      trace(rawData); returns something like

       

      [CODE]"1607":
              {
                  "key": "Xitan",
                  "value": "2283",
                  "isPremium": "0"
              },
          "1608":
              {
                  "key": "Xitron",
                  "value": "2284",
                  "isPremium": "0"
              },
          "1609": [/CODE]

       

      Now i´ve tried to bind this dataProvider for my first combobox listing all items with the value from "key" but my combobox stays blank/empty....

        • 1. Re: Populating JSON Data to Combobox - Need Help!
          Zolotoj Level 3

          How does the arr look like?

          • 2. Re: Populating JSON Data to Combobox - Need Help!
            li0uid Level 1

            trace(arr) returns "null"

            trace(dp) returns a blank output.

            trace(rawdata) returns

             

            "1624":
                    {
                        "key": "ZYX",
                        "value": "2309",
                        "isPremium": "0"
                    }
            }

             

            ...

             

            i tried some other json sources but allways the same...

            • 3. Re: Populating JSON Data to Combobox - Need Help!
              Zolotoj Level 3

              Here is how it is working for me:

              I useURLLoader to get JSON data.

              var loader:URLLoader = new URLLoader();

              loader.addEventListener(Event.COMPLETE, completeGetServerData);

              loader.load(request); // request points to your Web service. Personally I haven't done any Web Services

               

              private function completeGetServerData(event:Event):void
              {

                   obj = JSON.decode(event.target.data);

                   obj = objectToXML(obj);

                   dropdown.dataProvider = new XMLListCollection(obj.item);

              }

              private function objectToXML(obj:Object, qname:String="root"):XML
              {
                   var qName:QName = new QName(qname);
                   var xmlDocument:XMLDocument = new XMLDocument();
                   var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
                   var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
                   var xml:XML = new XML(xmlDocument.toString());
                   return xml;
              }

               

              HTH

              • 4. Re: Populating JSON Data to Combobox - Need Help!
                li0uid Level 1

                you treat it as XML? sorry. i am kind a new to this hole flex, as3 thang. could you tell me the import .. lines i need to include

                cause i got a lot of errors with your code like this.

                • 5. Re: Populating JSON Data to Combobox - Need Help!
                  Zolotoj Level 3

                  Here:

                       import com.adobe.serialization.json.JSON;
                     
                      import flash.display.DisplayObject;
                      import flash.events.*;
                      import flash.net.*;
                      import flash.utils.*;
                      import flash.xml.XMLDocument;
                      import flash.xml.XMLNode;
                      import mx.managers.PopUpManager;
                      import mx.collections.ArrayCollection;
                      import mx.core.FlexGlobals;
                      import mx.rpc.xml.SimpleXMLDecoder;
                      import mx.rpc.xml.SimpleXMLEncoder;
                      import mx.utils.ArrayUtil;

                   

                  Remove these you dont need.

                  • 6. Re: Populating JSON Data to Combobox - Need Help!
                    li0uid Level 1

                    Description    Resource    Path    Location    Type
                    1120: Access of undefined property completeGetServerData.    topdata.mxml    /topdata/src    line 21    Flex Problem
                    1120: Access of undefined property dropdown.    topdata.mxml    /topdata/src    line 28    Flex Problem
                    1120: Access of undefined property loader.    topdata.mxml    /topdata/src    line 21    Flex Problem
                    1120: Access of undefined property loader.    topdata.mxml    /topdata/src    line 22    Flex Problem
                    1120: Access of undefined property obj.    topdata.mxml    /topdata/src    line 26    Flex Problem
                    1120: Access of undefined property obj.    topdata.mxml    /topdata/src    line 27    Flex Problem
                    1120: Access of undefined property obj.    topdata.mxml    /topdata/src    line 28    Flex Problem
                    1120: Access of undefined property request.    topdata.mxml    /topdata/src    line 22    Flex Problem
                    1180: Call to a possibly undefined method XMLListCollection.    topdata.mxml    /topdata/src    line 28    Flex Problem

                    • 7. Re: Populating JSON Data to Combobox - Need Help!
                      li0uid Level 1

                      I tried the following now and it says "can´t convert obect@... to Array"  maybe there is something wrong with the JSON outout from the  webservice? But the JSON from the webservice validates, however if i test it with a small own JSON file locally it works...

                       

                      <?xml version="1.0" encoding="utf-8"?>
                      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                                      layout="absolute"
                                      minWidth="955" minHeight="600"
                                      applicationComplete="init()"
                                      frameRate="30">
                         
                          <mx:Script>
                              <![CDATA[
                                  import com.adobe.serialization.json.JSON;
                                 
                                  // var ini
                                  // ------------------------------------------------------------------------
                                  private var filePath:String = "http://dev.ws.topdata.de/data/tdifdata.php?Lookup=DeviceManufacturerId";
                                  private var urlLoader:URLLoader;
                                  private var jsonDataArray:Array;
                                  // ------------------------------------------------------------------------
                                 
                                 
                                  // ------------------------------------------------------------------------
                                  private function init():void
                                  {
                                      // Add event listener for button click
                                      btn.addEventListener(MouseEvent.CLICK,loadJSONFile);
                                  }
                                  // ------------------------------------------------------------------------
                                     
                                 
                                  // ------------------------------------------------------------------------
                                  private function loadJSONFile(e:MouseEvent=null):void
                                  {
                                      // Load file
                                      urlLoader = new URLLoader();
                                      urlLoader.addEventListener(Event.COMPLETE, fileLoaded,false,0,true);
                                      //urlLoader.addEventListener(IOErrorEvent.IO_ERROR, fileLoadFailed);
                                      urlLoader.load(new URLRequest(filePath));
                                  }
                                  // ------------------------------------------------------------------------
                                 
                                 
                                 
                                  // ------------------------------------------------------------------------
                                  private function fileLoaded(e:Event):void
                                  {
                                      // Clean up file load event listeners
                                      urlLoader.removeEventListener(Event.COMPLETE, fileLoaded);
                                     
                                      // If you wanted to get the data from the event use the line below
                                      //var urlLoader:URLLoader = URLLoader(event.target);
                                     
                                      // Parse the file to an array
                                      jsonDataArray = JSON.decode(urlLoader.data);
                                      trace(jsonDataArray);
                                     
                                      // Proceed to do something with the loaded data
                                      proceed();
                                  }
                                  // ------------------------------------------------------------------------
                                 
                                 
                                 
                                 
                                  // ------------------------------------------------------------------------
                                  private function proceed():void
                                  {
                                      // Retrieve data tests
                                      trace("jsonDataArray[0].name = " + jsonDataArray[0].name);
                                     
                                      // Populate data grid with our JSON Data
                                      dg.dataProvider = jsonDataArray;               
                                  }
                                  // ------------------------------------------------------------------------
                                 
                                 
                                 
                              ]]>
                          </mx:Script>
                         
                          <mx:DataGrid horizontalCenter="0" top="100" id="dg" width="400" height="200">
                              <mx:columns>
                                  <mx:DataGridColumn headerText="Key" dataField="key"/>
                                  <mx:DataGridColumn headerText="Value" dataField="value"/>
                              </mx:columns>
                          </mx:DataGrid>
                          <mx:Label text="An example of parsing JSON using AS3Corelib" color="#FFFFFF" fontWeight="bold" left="10" top="10" fontSize="14"/>
                          <mx:Button label="PARSE DATA INTO DATA GRID" horizontalCenter="0" top="70" width="400" id="btn"/>
                         
                      </mx:Application>

                      • 8. Re: Populating JSON Data to Combobox - Need Help!
                        Zolotoj Level 3

                        Try to put all the code into one mxml file.

                        • 9. Re: Populating JSON Data to Combobox - Need Help!
                          li0uid Level 1

                          hmm i did...

                           

                          maybe it´s cause i need to add the POST Parameters to access the webservices JSON Output but i added them like

                           

                                         urlLoader = new URLLoader();
                                          objRequest= new URLRequest();
                                          objRequest.url = 'http://dev.ws.topdata.de/data/tdifdata.php';
                                          objRequest.method = flash.net.URLRequestMethod.POST;
                                          objRequest.data = 'Lookup=DeviceManufacturerId';
                                          urlLoader.load(objRequest); 
                                          urlLoader.addEventListener(Event.COMPLETE, fileLoaded,false,0,true);
                                          //urlLoader.addEventListener(IOErrorEvent.IO_ERROR, fileLoadFailed);
                                          urlLoader.load(objRequest);

                           

                          now i got:

                           

                          JSONParseError: Unexpected F encountered

                          • 10. Re: Populating JSON Data to Combobox - Need Help!
                            Zolotoj Level 3

                            Where in the code are you getting this error? Did you check what's actually returning from the server?

                            • 11. Re: Populating JSON Data to Combobox - Need Help!
                              li0uid Level 1

                              I can´t see where the error happens actually but when i look at the url in the browser returning the JSON its just looking good. Also it validates as Valid JSON.

                               

                              Howevery if i try to load something local like "assets/my.json" it works well.

                               

                              See:

                              [
                                  {
                                      "product":"Spectrum 48K",
                                      "price":"£2.50"
                                  },
                                 
                                  {
                                      "product":"Spectrum 128K",
                                      "price":"£5.00"
                                  }
                              ]

                               

                              But my JSON i am trying to handle looks like:

                               

                              {      "0":            {                "key": "Brother",                "value": "306",                "isPremium": "1"           },      "1":            {                "key": "Canon",                "value": "351",                "isPremium": "1"           }, ...

                               

                              I never thought its hard as that just parsing some JSON from a webservice lol. I am really stucking at it.

                              • 12. Re: Populating JSON Data to Combobox - Need Help!
                                Zolotoj Level 3

                                Your code:

                                private function fileLoaded(e:Event):void
                                            {
                                                // Clean up file load event listeners
                                                urlLoader.removeEventListener(Event.COMPLETE, fileLoaded);
                                               
                                                // If you wanted to get the data from the event use the line below
                                                //var urlLoader:URLLoader = URLLoader(event.target);
                                               
                                                // Parse the file to an array
                                                jsonDataArray = JSON.decode(urlLoader.data);
                                                trace(jsonDataArray);
                                               
                                                // Proceed to do something with the loaded data
                                                proceed();
                                            }

                                 

                                and mine, which is very simple:

                                private function completeGetServerData(event:Event):void
                                {

                                     obj = JSON.decode(event.target.data);

                                }

                                Can you try using the same decoding?

                                • 13. Re: Populating JSON Data to Combobox - Need Help!
                                  li0uid Level 1

                                  If i change private var jsonDataArray:Array; to private var jsonDataObject:Object; i will get

                                   

                                  // Retrieve data tests

                                  trace ("jsonDataObject[0].name = " + jsonDataObject[0].key);

                                   

                                  //Output

                                  jsonDataObject[0].name = Brother

                                   

                                  But my Datagrid stay blank/empty

                                   

                                  Populate data grid with our JSON Data
                                  dg.dataProvider = jsonDataObject;  

                                   

                                  <mx:DataGrid horizontalCenter="0" top="100" id="dg" width="400" height="200">
                                          <mx:columns>
                                              <mx:DataGridColumn headerText="Key" dataField="key"/>
                                              <mx:DataGridColumn headerText="Value" dataField="value"/>
                                          </mx:columns>
                                      </mx:DataGrid>

                                  • 14. Re: Populating JSON Data to Combobox - Need Help!
                                    li0uid Level 1

                                    thanks for your words your code actually returns to the same (just tested)

                                     

                                    private function fileLoaded(event:Event):void
                                       {               
                                           jsonDataObject = JSON.decode(event.target.data);
                                           proceed();
                                       }

                                    • 15. Re: Populating JSON Data to Combobox - Need Help!
                                      li0uid Level 1

                                      combo.dataProvider = jsonDataObject;  

                                       

                                      returns to a combobox with id "combobox" and content of [object Object] instead of the manufacturer names...

                                      • 16. Re: Populating JSON Data to Combobox - Need Help!
                                        Zolotoj Level 3

                                        Ok, with DataGrid I am not sure you can use JSON directly. That's why I am using converting it to XML and then assigning dataPtovider:

                                        myGrid.dataProvider = new XMLListCollection(XmlData.elementName);

                                         

                                        use my code to turn JSON into XML and see if it works.

                                        • 17. Re: Populating JSON Data to Combobox - Need Help!
                                          li0uid Level 1

                                          well if i would like to use xml i just would read the xml from the webservice...

                                           

                                          maybe it´s because my JSON isn´t pushed to an Array correctly? Cause if i use Object instead it works fine but

                                          i can´t get the proper values inside a datagrid or combobox, maybe its to complex for it, at least it looks like

                                          or i don´t know how to handle it

                                          • 18. Re: Populating JSON Data to Combobox - Need Help!
                                            Zolotoj Level 3

                                            <maybe it´s because my JSON isn´t pushed to an Array correctly?

                                            Can you use ArrayCollection?

                                            • 19. Re: Populating JSON Data to Combobox - Need Help!
                                              li0uid Level 1

                                              its working as a ArrayCollection if my JSON would look like:

                                               

                                              [
                                                  { "key": "Brother", "value": "306", "isPremium": "1" }
                                              ]

                                               

                                              but the JSON output from the Webservice looks like:

                                               

                                              {    

                                                   "0":

                                                      { "key": "Brother", "value": "306", "isPremium": "1" }

                                              }

                                               

                                              {    

                                                   "1":

                                                      { "key": "Canon", "value": "302", "isPremium": "1" }

                                              }

                                               

                                              // but i have no control over the JSON output from the Webservice

                                               

                                              hmm...