AS3 从 PHP 解码 JSON 数据时出现问题
我可以使用以下代码将 JSON 数据从 PHP 提取到我的 Flex 应用程序中:
public function 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
}
}
当我跟踪结果时,我会看到我以正确的顺序提取的信息。
{"100":{"unit_price":"2.9567"},"400":{"unit_price":"1.0991"},"800":{"unit_price":"0.7926"},"1200": {“unit_price”:“0.6911”}} {
但是,一旦我 JSON.decode 结果,它就会以某种方式重新排序内容。并且,将第一项放在最后。
400:1.0991, 800:0.7926, 1200:0.6911, 100:2.9567
有谁知道为什么要这样做?或者关于如何自己重新排序对象的想法?
I am able to pull JSON data from PHP into my Flex application just fine with the following bit of code:
public function 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AS3 中的对象没有排序。 JSON 键值对显然确实有一个顺序(它在文本中!),但我认为在 JSON 编码或解码时不能保证它会被保留。
如果您有特定的订购要求,您可能应该创建一个包含对象的列表:
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:
在大多数情况下,Andrew 的答案是正确的,因为 AS3 中的对象是没有顺序的。但是我不会创建对象列表;相反,我会创建一个用于索引 JSON 对象的键列表。这样就可以轻松对键列表进行排序。
我所得到的代码是这样的:
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: