有什么办法才去code,以验证JSON?有什么办法、才去、JSON、code

2023-09-08 12:53:29 作者:陌墨

我有一个应用程序,下载一个文件,然后去code期待它的JSON格式,当格式是确定一切顺利。如果我故意乱JSON文件快报格式错误,并停止该应用程序。有没有一种方法来处理错误?

I have an app that download a file and then decode it expecting a JSON format, when the format is ok everything goes well. If i intentionally mess the json file flash reports a format error and stop the app. Is there a way to handle the error?

code:

import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

import com.adobe.serialization.json.JSON;


public class Main extends Sprite 
{

    private var _jsonPath:String = "json_example.txt";

    public function Main():void 
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);

        var loader:URLLoader = new URLLoader();
        var request:URLRequest = new URLRequest();
        request.url = _jsonPath;
        loader.addEventListener(Event.COMPLETE, onLoaderComplete);
        loader.load(request);
    }


    private function onLoaderComplete(e:Event):void 
    {
        var loader:URLLoader = URLLoader(e.target);
            var jsonArray:Array = JSON.decode(loader.data);
  }

您看我的问题是,就在年底,其中 VAR jsonArray:阵列= JSON.de code(loader.data); 如何处理我的code。如果失败了?

You see my problem is right at the end where var jsonArray:Array = JSON.decode(loader.data); How can I handle in my code if that fails?

推荐答案

使用尝试..赶上......

Use try.. catch...

import com.adobe.serialization.json.JSONParseError;

try
{
var jsonArray:Array = JSON.decode(loader.data);
}
catch ( e:JSONParseError )
{
    //do something
    trace(e);
}
finally
{
}

该解决方案使用的as3corelib( HTTP://as3corelib.google$c$c.com/ ),如果你使用JSON.parse()请从JayC答案

This solution uses as3corelib (http://as3corelib.googlecode.com/), if you use JSON.parse() please check the answer from JayC