AS3 Problem with decoding JSON data from PHP
I am able to pull JSON data from PHP into my Flex application just fine with the following bit of code:
public funct开发者_开发百科ion httpResult(event:ResultEvent):void {
var rawData:String = String(event.result);
trace(String(event.result)); //shows correct order
var as3Data:Object = JSON.decode(rawData);
for (var i:* in as3Data) {
trace(i + ": " + as3Data[i].unit_price); //shows incorrect order
}
}
When I trace the result, I see the information I am pulling in the correct order.
{"100":{"unit_price":"2.9567"},"400":{"unit_price":"1.0991"},"800":{"unit_price":"0.7926"},"1200":{"unit_price":"0.6911"}} {
But, once I JSON.decode the result, somehow it re-orders the content. And, puts the first item last.
400: 1.0991, 800: 0.7926, 1200: 0.6911, 100: 2.9567
Does anyone have any ideas on why it would be doing this? Or ideas on how I can re-order the Object myself?
Objects in AS3 aren't ordered. JSON key-value pairs obviously do have an ordering (it's in the text!), but I don't think there's any guarantee it'll be kept when the JSON is either encoded or decoded.
If you've got specific ordering requirements, you should probably create a list with objects in it:
[
{"100":{"unit_price":"2.9567"}},
{"400":{"unit_price":"1.0991"}},
{"800":{"unit_price":"0.7926"}},
{"1200":{"unit_price":"0.6911"}}
]
For the most part Andrew's answer is right on, because yeah objects in AS3 aren't ordered. However I wouldn't create a list of objects; rather I would create a list of keys used to index into the JSON object. That way it's easy to sort the list of keys.
The code for what I'm getting at is something like:
var as3Data:Object = JSON.decode(rawData);
var keys:Array = [];
for (var i:* in as3Data) {
keys.push(i);
}
keys.sort(); //don't know the correct sort off the top of my head, sorry
for (var key:* in keys) {
trace(key + ":" + as3Data[key].unit_price);
}
精彩评论