添加JSON作为资产并读取它 [英] Adding JSON as asset and reading it

查看:96
本文介绍了添加JSON作为资产并读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to load some JSON data from a local file.

此Apple文档中说:

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

Manage the data files for your app using the asset catalog. A file can contain any sort of data except device executable code generated by Xcode. You can use them for JSON files, scripts, or custom data types

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

So I added a new data set and dropped the JSON file inside. Now I can see it under Assets.xcassets folder (Colours.dataset folder with colours.json and Contents.json inside it)

我找到了 SO答案,该答案显示了如何阅读JSON文件,我正在使用以下代码读取文件:

I found this SO answer that shows how to read a JSON file and I'm using this code to read the file:

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",但无济于事.

But this code is printing "Invalid file path" and not reading the file. I also tried "Colours" and "Colours.json" but to no avail.

任何人都可以告诉我如何正确添加本地JSON文件并读取它吗?

Could anyone please tell me how to properly add a local JSON file and read it?

谢谢.

推荐答案

您不能以与使用NSBundle.pathForResource访问随机文件相同的方式访问数据资产文件.由于只能在Assets.xcassets中定义它们,因此您需要初始化NSDataAsset实例才能访问其内容:

You can't access data asset files in the same way you access a random file using NSBundle.pathForResource. Since they can only be defined within Assets.xcassets, you need to initialize a NSDataAsset instance in order to access the contents of it:

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.

Please note that NSDataAsset class was introduced as of 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中,因此请不要忘记在代码中导入相关框架:

Also, NSDataAsset is surprisingly located in UIKit/AppKit so don't forget to import the relevant framework in your code:

#if os(iOS)

    import UIKit

#elseif os(OSX)

    import AppKit

#endif

这篇关于添加JSON作为资产并读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆