AS3 JSON parsing

╄→гoц情女王★ 提交于 2019-12-21 04:25:14

问题


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:

[
    {
        "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!


回答1:


from flash player 11, and sdk 4.6 there is native support for json. To use it you should change

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 ;)




回答2:


You will need to use the JSON Object Class (below link) 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"}



回答3:


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);
  }
}



回答4:


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.

function json_decode( data:String ):* {
  try {
    return ExternalInterface.call("function(){return " + data + "}");
  } catch (e:Error) {
    return null;
  }
}


来源:https://stackoverflow.com/questions/1713479/as3-json-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!