Flex Webservices XML and Array Conversion
I'm currently working on a project involving simple webservices, the webservices return plain XML rather than using SOAP. Personally I prefer SOAP as you get a well defined interface but on this project it was felt that plain XML was less verbose, more efficient and easy to code server side.
Anyway one of the issues with returning XML via HTTPService calls is that when flex converts the XML to objects it treats it as array if there's more than one item of the same name but as a single item (ie not an array) if there's only one item of the same name.
This causes databinding to datagrids or lists to fail.
So how do you get around this issue?
Let's say our HTTPService call is returning XML like this:
2<user>Andy</user>
3<user>Betty</user>
4<user>Cathy</user>
5<user>Dave</user>
6</users>
But sometimes only one user is returned like this:
2<user>Fred</user>
3</userd>
If the first case the user will be treated as an ArrayCollection but in the second it's just an Object.
Here the code that can deal with both:
2
3if (data is ArrayCollection) {
4 userlist = data;
5}
6else {
7 userlist = new ArrayCollection([data])
8}
I have since found out that you can do it like so:
but I think I prefer the first method.
var data:Object = event.result.users.user
if (data is ArrayCollection) {
userlist = ArrayCollection(data);
}
else {
userlist = new ArrayCollection([data])
}