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 !
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.
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.
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
.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With