【问题标题】:Adding JSON as asset and reading it将 JSON 添加为资产并读取它
【发布时间】:2015-11-09 21:17:10
【问题描述】:

我正在尝试从本地文件加载一些 JSON 数据。

this Apple doc 中写道:

使用资产目录管理您的应用的数据文件。一个文件可以 包含除由生成的设备可执行代码之外的任何类型的数据 Xcode。 您可以将它们用于 JSON 文件、脚本或自定义数据类型

所以我添加了一个新数据集并将 JSON 文件放入其中。现在我可以在 Assets.xcassets 文件夹下看到它(Colours.dataset 文件夹,里面有 colours.json 和 Contents.json)

我找到了this SO 答案,它显示了如何读取 JSON 文件,我正在使用此代码读取文件:

if let filePath = NSBundle.mainBundle().pathForResource("Assets/Colours", ofType: "json"), data = NSData(contentsOfFile: filePath) {

        print (filePath)

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            print(json)
        }
        catch {

        }
    } else {
        print("Invalid file path")
    }

但是这段代码正在打印“无效的文件路径”,而不是读取文件。我也尝试了“Colours”和“Colours.json”,但无济于事。

谁能告诉我如何正确添加本地 JSON 文件并阅读它?

谢谢。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您无法像使用NSBundle.pathForResource 访问随机文件一样访问数据资产文件。由于它们只能在Assets.xcassets 中定义,因此您需要初始化一个NSDataAsset 实例才能访问它的内容:

    let asset = NSDataAsset(name: "Colors", bundle: NSBundle.mainBundle())
    let json = try? NSJSONSerialization.JSONObjectWithData(asset!.data, options: NSJSONReadingOptions.AllowFragments)
    print(json)
    

    请注意,NSDataAsset 类是从 iOS 9.0 和 macOS 10.11 开始引入的。

    Swift3 版本:

    let asset = NSDataAsset(name: "Colors", bundle: Bundle.main)
    let json = try? JSONSerialization.jsonObject(with: asset!.data, options: JSONSerialization.ReadingOptions.allowFragments)
    print(json)
    

    另外,令人惊讶的是,NSDataAsset 位于 UIKit/AppKit 中,所以不要忘记在代码中导入相关框架:

    #if os(iOS)
    
        import UIKit
    
    #elseif os(OSX)
    
        import AppKit
    
    #endif
    

    【讨论】:

      【解决方案2】:

      objC

      #ifdef use_json_in_bundle
                  NSString * path = [mb pathForResource:json_path ofType:@"json" inDirectory:@"JSON"];
                  NSString * string = [NSString stringWithContentsOfUTF8File:path];
                  NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];
      #else
                  NSDataAsset * asset = [[NSDataAsset alloc] initWithName:path];
                  NSLog(@"asset.typeIdentifer = %@",asset.typeIdentifier);
                  NSData * data = [asset data];
      #endif
                  NSError * booboo = nil;
                  id blob = [NSJSONSerialization JSONObjectWithData:data options:0 error:&booboo];
      

      对于任一分支,“路径”只是 json 文件名。

      【讨论】:

        猜你喜欢
        • 2022-09-27
        • 2018-02-26
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多