【问题标题】:Flash Builder will not read local JSON file . .Flash Builder 不会读取本地 JSON 文件。 .
【发布时间】:2012-01-11 22:00:16
【问题描述】:

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

我已经在 Google 上搜索过很多次了,但是每个显示如何在 Flash Builder 中使用 JSON 文件的示例都使用 HTTP 服务,指向网络上的一个文件。

我在这里,坐在我的 MacBook 前,想知道为什么我不能完成这项工作。在我找到的文档中(有点与这个问题有关),它们总是显示 Windows 示例,而且它们似乎工作正常:

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

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

我试过了

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

这行不通。我尝试了一些“解析到路径”语法,但 HTTP 服务似乎只允许使用引号中的文件路径。

有谁能帮我指出正确的方向吗?

【问题讨论】:

  • 是的。最后我希望它是一个 AIR 应用程序。

标签: json apache-flex flash-builder


【解决方案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 上同样适用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2018-06-25
    • 2017-07-07
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多