How to parse JSON (AS3)

2019-02-13 00:39发布

How to parse downloaded .json file with a string inside it to a string variable? With as3corelib.swc.

2条回答
三岁会撩人
2楼-- · 2019-02-13 01:30

The function for parsing JSON using as3corelib ( ie not the native JSON class ) is 'decode()'

JSON.decode( inputJson );

If the input json is properly encoded, strings should be available inside the resulting object. You may have trouble parsing strings if they have not been correctly escaped, but that is a problem with the input data.

查看更多
SAY GOODBYE
3楼-- · 2019-02-13 01:38

And here we go, full-working example from my current project:

protected function loadConfigFromUrl():void
{
    var urlRequest:URLRequest  = new URLRequest(CONFIG_URL);

    var urlLoader:URLLoader = new URLLoader();
    urlLoader.addEventListener(Event.COMPLETE, completeHandler);

    try{
        urlLoader.load(urlRequest);
    } catch (error:Error) {
        trace("Cannot load : " + error.message);
    }
}

private static function completeHandler(event:Event):void {
    var loader:URLLoader = URLLoader(event.target);
    trace("completeHandler: " + loader.data);

    var data:Object = JSON.parse(loader.data);
    trace("The answer is " + data.id+" ; "+data.first_var+" ; "+data.second_var);
    //All fields from JSON are accessible by theit property names here/
}
查看更多
登录 后发表回答