Develop a mechanism for parsing JSON request result with unknown schema into DataGrid columns.
Use com.adobe.serialization.json to parse JSON request into array and ObjectUtil.getClassInfo to obtain array item object schema.
Sample project attached to this recipe.
First of all we need to download and add to our project com.adobe.serialization.json package. After JSON result obtained we had to decode it into array of objects, obtain it's elements properties list and add to DataGrid instance as much columns as properties array item has. For each column we should set dataField property to corresponding element property. After this we should cover array into ArrayCollection and set it as DataGrid data provider.
Sample application looks 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.controls.dataGridClasses.DataGridColumn;
import mx.utils.ObjectUtil;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;
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);
//obtain array elements schema using ObjectUtil
var schema:Object = ObjectUtil.getClassInfo(arr[0]);
for each(var token:Object in schema.properties) {
var data:String = token.toString();
var col:DataGridColumn = new DataGridColumn(data);
col.dataField = data;
grid.columns.push(col);
}
//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;
}
private function onJSONFault(evt:FaultEvent):void {
trace(evt.message);
}
]]>
</mx:Script>
<mx:HTTPService id="service" resultFormat="text"
url="http://codeflex.ru/services/jsonsample.js"
result="onJSONLoad(event)" fault="onJSONFault(event)"/>
<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10"
/>
</mx:Application>