Flash Builder不会读取本地JSON文件。 。

时间:2012-01-11 22:00:16

标签: json flex flash-builder

所以我尝试构建一个小实用程序,以易于理解的方式查看JSON文件的内容(对于非技术人员)。

我已经Google搜索了广泛,高低,但每个显示如何在Flash Builder中使用JSON文件的示例都使用HTTP服务,指向Web上的文件。

我坐在我的MacBook前面,想知道为什么我不能做这个工作。在我发现的文档中(与此问题有关),它们总是显示Windows示例,它们似乎工作正常:

C://me/projects/json/my_json.json

也许我完全错过了显而易见的事情,但这在Mac上是否可行?

我试过

file:///Users/me/projects/json/my_json.json

这不起作用。我尝试了一些“解决路径”语法,但HTTP服务似乎不允许除引号中的文件路径之外的所有内容。

有人能够朝着正确的方向努力吗?

1 个答案:

答案 0 :(得分:1)

使用File API。这很简单,这是一个快速的代码示例:

// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;

// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);

// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");

// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);

// Select event handler
private function onSelect(e:Event):void
{
   // Remove listeners on e.currentTarget
   // ...

   // Cast to File
   var selectedFile:File = e.currentTarget as File;
   readFile(selectedFile);
}

private function onCancel(e:Event):void
{
    // Remove listeners on e.currentTarget
    // ...
}

private function readFile(file:File):void
{
   // Read file
   var fs:FileStream = new FileStream();
   fs.open(selectedFile, FileMode.READ);
   var contents:String = fs.readUTFBytes(selectedFile.size);
   fs.close()

   // Parse your JSON for display or whatever you need it for
   parseJSON(contents);
}

您在帖子中暗示了有关Windows的示例以及您在Mac上的说明,但我会在此明确说明:您应该始终使用File API,因为它是跨平台的。此代码在Windows和Mac上同样有效。