AS3 JSON 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1713479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AS3 JSON parsing
提问by dtrainer45
I have a bit of a dilemma. I have a JSON object that has a format I'm unfamiliar with (starts with an array []instead of an object {}) and was wondering how I might parse it in AS3. The object looks like:
我有点进退两难。我有一个 JSON 对象,它的格式我不熟悉(以数组[]而不是对象开头{}),我想知道如何在 AS3 中解析它。该对象看起来像:
[
{
"food": [
{
"name": "pasta",
"price": 14.50,
"quantity": 20
},
{
"name": "soup",
"price": 6.50,
"quantity": 4
}
]
},
{
"food": [
{
"name": "salad",
"price": 2.50,
"quantity": 3
},
{
"name": "pizza",
"price": 4.50,
"quantity": 2
}
]
}
]
I don't really know how I get to each food array, and each object within it. Any help would be greatly appreciated! Thanks!
我真的不知道如何到达每个食物阵列以及其中的每个对象。任何帮助将不胜感激!谢谢!
回答by PiotrkS
from flash player 11, and sdk 4.6 there is native support for json. To use it you should change
从 Flash Player 11 和 sdk 4.6 开始,原生支持 json。要使用它,你应该改变
var foods:Array = JSON.decode(jsonstring);
to
到
var foods:Array = JSON.parse(jsonstring);
while JSON is not from as3corelib but from sdk itself. Pretty much faster ;)
而 JSON 不是来自 as3corelib,而是来自 sdk 本身。快得多;)
回答by medoix
You will need to use the JSON Object Class (below link) http://code.google.com/p/as3corelib/
您将需要使用 JSON 对象类(以下链接) http://code.google.com/p/as3corelib/
and then something like this..
然后像这样..
var data:String = "{\"name\":\"pizza\",\"price\":\"4.50\",\"quantity\":\"2\"}";
var food:JSONObject = new JSONObject(data);
trace(food.name); // Pizza
trace(food.price); // 4.50
trace(food.quantity); // 2
food.number++;
var newData:String = String(food);
trace(newData); // {"name":"pizza","price":"4.50","quantity":"2"}
回答by Les
Interesting datastructure... this should do it:
有趣的数据结构......这应该这样做:
import com.adobe.serialization.json.JSON;
/* ... other code ... */
var foods:Array = JSON.decode(jsonstring);
for(var i:int = 0; i < foods.length; i++) {
for(var j:int = 0; j < foods[i].length; j++) {
trace(foods[i][j].name);
}
}
回答by Shane
I was looking for an alternative to a library and found the technique here. I'm assuming this will work in the context of the op (which was answered years ago of course) since it doesn't require a return type of Object. This works well for what I was trying to do when I found this post and I found the solution pretty elegant for flash based in the browser.
我正在寻找图书馆的替代品,并在此处找到了该技术。我假设这将在 op 的上下文中工作(当然是几年前回答的),因为它不需要返回类型的 Object。当我发现这篇文章时,这对我正在尝试做的事情很有效,我发现基于浏览器的 Flash 的解决方案非常优雅。
function json_decode( data:String ):* {
try {
return ExternalInterface.call("function(){return " + data + "}");
} catch (e:Error) {
return null;
}
}

