It was an old problem that it happened again some days ago while supporting a client for a Flex 2 application.
You know that when you call the HTTPService class and it returns the response data, you can type casting them in ArrayCollection with the following code :
<mx:HTTPService id="myHS" url="data/states.xml"
result="myAC = myHS.lastResult.dataroot.city as ArrayCollection" />
Now you're ready to use it in data binding with Flex 2 controls.
But if the response data returns an XML with only one item, you'll get the following error :
"cannot convert mx.utils::ObjectProxy@36fbf81 to mx.collections.ArrayCollection"
This is the sample response xml data:
<dataroot>
<city>
<id>22</id>
<region>TRENTINO ALTO ADIGE</region>
<city>TRENTO</city>
<population>449852</population>
</city>
</dataroot>
So you can use a result handler to better handle the error :
<mx:HTTPService id="myHS" url="data/states.xml"
result="resultHandler(event)" />
private function resultHandler(event :ResultEvent ) :void {
if( event.result.dataroot.city == null ) {
mx.controls.Alert.show("The response data are empty !");
}
else if ( event.result.dataroot.city is ObjectProxy ) {
// the response date has only one item
myAC = new ArrayCollection( [event.result.dataroot.city ] );
}
else {
myAC = event.result.dataroot.city as ArrayCollection;
}
}
You cal also use the ArrayUtil.toArray() method to force the type conversion :
myAC = new ArrayCollection(ArrayUtil.toArray(event.result.dataroot.city));
Hope that helps.
Thanks to Francesco for finding the solution on my old post, under comments ;)






















Also I think resultFormat="array" will do the trick for you to force it into an array all the time.
Posted by: Matt | March 15, 2007 at 07:47 PM
I have seen this problem when using WebService and resultFormat="object". And the workaround used is as mentioned in the post- check for ArrayCollection etc.
I have also found cases where the result is an Array even if there is only one object- but the XSD in both cases look exactly the same.
But given that the WebService is backed by a WSDL and XSD schema that defines the result format this feels more like a hack/workaround.
Posted by: ajit parthan | March 15, 2007 at 10:18 PM
I haven't had time to test this code with xml, but wouldn't this do it as well.
private function resultHandler(event :ResultEvent ) :void
{
var myAC:ArrayCollection;
if( event.result.dataroot.city == null )
{
mx.controls.Alert.show("The response data are empty !");
}
else
{
myAC = new ArrayCollection(event.result.dataroot.city as Array);
}
}
Posted by: Robert Stark | March 16, 2007 at 04:32 AM
Thanks Matt ;) !
Posted by: Marco Casario | March 16, 2007 at 11:33 AM
hey, this is a great post i have the same problem witch 1 item result, and i resolve with you code.
Grettins from Argentina.
Posted by: Martin | October 24, 2007 at 02:02 AM