INCLUDE_DATA

Custom value objects serialization

I have been doing a lot of Flex work over the last couple of months. One of the biggest challenge was serialization value objects to XML. On beginning I thought it must be very easy, just implement the ActionScript-based flash.utils.IExternalizable interface… but it did not work together with Cairngorm Value Objects.

So, I have decided to write my own custom procedure which converts any Cairngorm Value Objects to XML. ValueObject class may contain not only primitive data types like String, int, Number but also items list and any custom class members. The following procedure enumerates all value objects fields, uses field name as tag and field value as xml tag value.


/**
* Converts object class to XML format.
*/
public  function objectToXml(obj : Object, name : String) : XML {

	var result 	: XML;
	var info		: Object = ObjectUtil.getClassInfo(obj,["myExcludesArray"]);
	var className	: String = getQualifiedClassName(obj);

	if (name==null) name = info.name;

	if (className == "mx.collections::XMLListCollection") {
		result = new XML("<" + name + ">" + obj.toXMLString() + "</"+ name + ">");
		return result;
	};								

	result = new XML("<" + name + "></"+ name + ">");

	for each (var qn : QName in info.properties){

		var val : Object = obj[qn.toString()];

		if (ObjectUtil.isSimple(val)) {

			result[qn.toString()] = val; 

		}
		else {

			result.appendChild(objectToXml(val,qn.toString()));

		}	 

	}

	return result;
}	

The following example show the complete source code for serializing Carnigorm Value Objects to XML.

View source is enabled in the following example.