Skip to content

Instantly share code, notes, and snippets.

@sinnus
Created January 3, 2012 20:14
Show Gist options
  • Save sinnus/1556693 to your computer and use it in GitHub Desktop.
Save sinnus/1556693 to your computer and use it in GitHub Desktop.
package
{
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import mx.utils.ObjectUtil;
public class Converter
{
private static var _simpleTypes: Array = [Boolean, Number, String];
private static function populateArray(data: Array, clazz: Class): Array
{
var result: Array = new Array(data.length);
for (var i: int =0; i< data.length; i++) {
result[i] = createData(data[i], clazz);
}
return result;
}
private static function createData(rawData: Object, clazz: Class): *
{
if (clazz == Object) {
return rawData;
}
if (rawData != null) {
if (_simpleTypes.indexOf(clazz) > -1) {
return rawData;
} else {
var result: Object = new clazz();
var describeTypeXML:XML = describeType(clazz);
for each (var variable: XML in describeTypeXML..variable)
{
processVar(variable, rawData, result);
}
for each (var accessor: XML in describeTypeXML..accessor)
{
if (accessor.@access == "readwrite")
{
processVar(accessor, rawData, result);
}
}
return result;
}
}
return null;
}
private static function processVar(variable:XML, rawData:Object, result:Object):void
{
if (variable.@type == "Array") {
var array: Array = rawData[variable.@name];
if (array) {
var metaType: Class = Object;
for each (var metadata: XML in variable..metadata) {
if (metadata.@name == "ArrayElementType") {
metaType = getDefinitionByName(metadata..arg.@value) as Class;
}
}
result[variable.@name] = populateArray(array, metaType);
}
} else {
result[variable.@name] = createData(rawData[variable.@name], getDefinitionByName(variable.@type) as Class)
}
}
public static function convertData(rawData: Object, clazz: Class): *
{
if (rawData === null) {
return null;
}
if (describeType(rawData).@name == "Array") {
return populateArray(rawData as Array, clazz);
} else {
return createData(rawData, clazz);
}
}
public static function toRawData(object: *): Object {
if (object === null) {
return null;
}
for each (var clazz : Class in _simpleTypes) {
if (object is clazz) {
return object;
}
}
if (object is Array) {
var arrayResult: Array = [];
for each (var item: Object in object) {
arrayResult.push(toRawData(item));
}
return arrayResult;
}
var result: Object = {};
var classInfo: Object = ObjectUtil.getClassInfo(object);
for each (var p: String in classInfo.properties) {
result[p] = toRawData(object[p]);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment