Adding JSON as an asset and reading it

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

This Apple document says:

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

So, I added a new dataset and deleted the JSON file inside. Now I see this in the Assets.xcassets folder (the Colours.dataset folder with colours.json and Contents.json inside it)

I found this SO answer that shows how to read a JSON file, and I use 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") } 

But this code prints "Invalid file path" and does not read the file. I also tried Colors and Colors.json, but to no avail.

Can someone tell me how to properly add a local JSON file and read it?

Thanks.

+6
source share
2 answers

You cannot access data data files in the same way as a random file using NSBundle.pathForResource . Since they can only be defined in Assets.xcassets , you need to initialize an instance of NSDataAsset in order to access its contents:

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

Note that the NSDataAsset class was introduced as iOS 9.0 and macOS 10.11.

Swift3 version:

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

In addition, NSDataAsset is surprisingly located in UIKit / AppKit, so be sure to import the appropriate structure into your code:

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

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]; 

for any branch, the path is just the json file name.

0
source

All Articles