Archive

Posts Tagged ‘Actionscript’

Converting XML data to strongly typed AS3 Object

February 18, 2009 Leave a comment

Context / Problem :

The Use of the HttpService gives us the opportunity to retreive XML data from a server.
But … the problem starts when we receive these data : how could we manipulate these data from a strongly typed manner ?
Let’s take an example to illustrate the issue :

The following code retrieves xml data and registers a callback to parse the result :

var httpService:HTTPService = new HTTPService();
httpService.addEventListener(ResultEvent.RESULT, onLoadListResult);
httpService.url="TodoItems.xml";
httpService.resultFormat=HTTPService.RESULT_FORMAT_OBJECT;
httpService.send();

private function onLoadListResult(e:ResultEvent):void {
	var resultList:ArrayCollection = new ArrayCollection();
	for each (var o:ObjectProxy in  ArrayCollection(e.result.List.TodoItemVO)) {
		trace(o.title);
	}
}

The content of TodoItems.xml is the following :

<?xml version="1.0" encoding="utf-8"?>
<List>
	<TodoItemVO>
		<id>1</id>
		<title>Simple title</title>
		<detail>detail</detail>
	</TodoItemVO>
	<TodoItemVO>
		<id>2</id>
		<title>another Title</title>
		<detail>detail2</detail>
	</TodoItemVO>
</List>

So the output for this will be the following :

Simple title
another Title

It works … so where is the issue ?
Well what I would like is to cast the result in strongly type object.
The direct solution would be to create my typed object and copy each attribut in it.
My callback function would be something like this :

private function onLoadListResult(e:ResultEvent):void {
	var resultList:ArrayCollection = new ArrayCollection();
	for each (var o:ObjectProxy in  ArrayCollection(e.result.List.TodoItemVO)) {
		var todoItemVO:TodoItemVO = new TodoItemVO();
		todoItemVO.id = o.valueOf().id;
		todoItemVO.title = o.valueOf().title;
		todoItemVO.detail = o.valueOf().detail;
		resultList.addItem(todoItemVO);
	}
}

But what if I have more than 3 attributes to copy ?

Solution :

I’ve found this solution from the Darron Schall blog’s in this blog entry :

He has developped an utility object (ObjectTranslator) that will copy your data in the strongly typed object with only one line of code :

ObjectTranslator : converts a plain vanilla object to be an instance of the class passed as the second variable.  This is not a recursive funtion and will only work for the first level of nesting.  When you have deeply nested objects, you first need to convert the nested objects to class instances, and then convert the top level object.

My code will then look like this :

private function onLoadListResult(e:ResultEvent):void {
	var resultList:ArrayCollection = new ArrayCollection();
	for each (var o:ObjectProxy in  ArrayCollection(e.result.List.TodoItemVO)) {           
		resultList.addItem(ObjectTranslator.objectToInstance(o.valueOf(), TodoItemVO) as TodoItemVO);
	}
}

Advertisements
Categories: Actionscript Tags: ,