2013-04-06 73 views
0

Im試驗如何在Flex 4.6中創建自定義項目渲染器,並使用JSON格式的數據源...使用以下命令檢索json數據,並且它能正常工作,並且我可以訪問數據如何加載JSON數據並將其用作dataGroup的dataProvider?

myJSONdata[i].id 
myJSONdata[i].username etc... 

但是我在理解如何使這個數據成爲flex的數據類型(ArrayList,ArrayCollection?)以分配給dataGroup的dataProvider時遇到問題。

public var loader:URLLoader = new URLLoader(); 
public var jsonContent:URLLoader; 
public var myJSONdata:Object; 
public var request:URLRequest; 

public function Init():void { 

request = new URLRequest("URL TO THE JSON DATA..."); 
loader.load(request); 
loader.addEventListener(Event.COMPLETE, jsonLoaded); 
} 


public function jsonLoaded(event:Event):void { 

jsonContent = URLLoader(event.target);  
myJSONdata = JSON.parse(jsonContent.data); 

trace(myJSONdata.length);    

} 

當我嘗試分配這樣的數據提供程序...

<s:DataGroup dataProvider="myJSONdata"> 

我得到這個錯誤:

Initializer for 'dataProvider': values of type mx.collections.IList cannot be represented in text. 

我想使用相同的數據訪問功能和然後讓這些數據充當一個數組,然後我可以將其用作dataGroup的dataProvider。

回答

1

要麼給你DATAGROUP和ID,並指定數據提供程序在AS3這樣的:

<s:DataGroup id="myDataGroup"> 

//in as3 

myDataGroup.dataProvider = new ArrayCollection(myJSONdata); 

或者就像你在MXML做,但必須在大括號包裹變量名可以分配給它。

<s:DataGroup dataProvider="{myJSONdata}"> 

爲什麼你得到這個錯誤的原因是因爲MXML是治療myJSONdata作爲一個正常的字符串。

您可能仍然需要將JSON數組放在ArrayCollection中,就像我對第一個示例所做的那樣。

希望有所幫助。

+0

感謝您的幫助......當我嘗試 myDataGroup.dataProvider =新ArrayCollection的(myJSONdata); 我收到此錯誤消息... 將靜態類型對象的值隱式強制爲可能不相關的類型數組。 – tamak 2013-04-06 14:20:42

+0

如果你的myJSONdada是一個數組,你可以做'myDataGroup.dataProvider = new ArrayCollection(myJSONdata as Array);'如果它不是一個數組,你將需要遍歷它並在創建一個'ArrayCollection'前將它的元素添加到數組中 – 2013-04-06 14:35:33

+0

PERFECT ...終於可以看到數據...現在我繼續嘗試學習如何做自定義的itemrenderers ...感謝您的幫助@Ban – tamak 2013-04-06 14:58:06

0

儘管這篇文章很舊,但這仍然有用,也許對其他人有用。

<fx:Declarations> 
    <!-- Place non-visual elements (e.g., services, value objects) here --> 
    <s:HTTPService id="jsonLoader" result="jsonLoader_resultHandler(event)" 
        url="http://example.com/sample.json" /> 
</fx:Declarations> 
<fx:Script> 
    <![CDATA[ 
     import com.adobe.serializers.json.JSONDecoder; 

     import mx.collections.ArrayCollection; 
     import mx.rpc.events.ResultEvent; 

     //<s:WindowedApplication .... creationComplete="initApp()"> 
     public function initApp():void 
     { 
      //so trigger jsonLoader to load the json data from the link 
      // using the HTTPService immediately the application starts; 
      jsonLoader.send(); 
     } 

     protected function jsonLoader_resultHandler(event:ResultEvent):void 
     { 
      var jsonContent:Object = (new JSONDecoder()).decode(event.result.toString()); 
      //Assuming jsonContent.data is an Array 
      resultDataGrid.dataProvider = new ArrayCollection(jsonContent.data); 
     } 
    ]]> 
</fx:Script> 
相關問題