Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to place and handle .json file in Xcode

Tags:

json

xcode

swift

I just started to learn Swift and xcode and the first problem that I'm facing is how and where should I place the json file ? And how to use those files? Should I place the .json files within Assets folder ? Since I find it difficult, I would love to hear some tips or examples from you !

like image 593
Jennifer Avatar asked Dec 28 '15 12:12

Jennifer


People also ask

Where do I put JSON files in Xcode project?

To add the JSON file to your project, you can just drag and drop it inside Xcode: After adding the JSON file to your project, head to the ContentView. swift file. This is where we will read the JSON list and update the interface with our data.

How use JSON file in IOS Swift?

if let path = Bundle. main. path(forResource: "assets/test", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: . alwaysMapped) let jsonObj = try JSON(data: data) print("jsonData:\(jsonObj)") } catch let error { print("parse error: \(error.


2 Answers

You can add an empty file, select syntax coloring as JSON and paste your json text. Even if it is not formatted, you can format it by selecting all the text and pressing Ctrl + I.

enter image description here

like image 50
Denis Kutlubaev Avatar answered Oct 20 '22 00:10

Denis Kutlubaev


Please review the below image to check where to place the file. I suggest you to create a group and add the file in that.enter image description here

After that, review the below could for using that file.

Edit: This is the updated code for Swift 5 if that helps anyone.

    let path = Bundle.main.path(forResource: "filename", ofType: "json")
    let jsonData = try? NSData(contentsOfFile: path!, options: NSData.ReadingOptions.mappedIfSafe)
like image 43
Sukhdeep Singh Kalra Avatar answered Oct 19 '22 23:10

Sukhdeep Singh Kalra