Reputation: 1852
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 !
Upvotes: 22
Views: 39713
Reputation: 403
How I've done this in September 2019...
1) In Xcode, create an Empty
file. Give the file a .json
suffix
2) Type in or paste in your JSON
3) Click Editor
-> Syntax Coloring
-> JSON
4) Inside the file, highlight the JSON, click ctrl + i
to indent
5) import SwiftyJSON
using Cocoapods
6) In your ViewController, write...
guard let path = Bundle.main.path(forResource: "File", ofType: "json") else { return }
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSON(data: data)
} catch {
print(error)
}
N.B. - "File"
is the name of the file you created, but excluding the .json
suffix
See SwiftyJSON GitHub page for more info - https://github.com/SwiftyJSON/SwiftyJSON
Upvotes: 17
Reputation: 827
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)
Upvotes: 8
Reputation: 16124
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
.
Upvotes: 28
Reputation: 151
var location = "test"
var fileType = "json"
if let path = Bundle.main.path(forResource: location, ofType: fileType) {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
}
} catch let error {
print(error.localizedDescription)
}}
Upvotes: 4
Reputation: 827
As per your requirement, you want to read json from that json file.
I am using SWIFTY JSON Library for that.
Find below the link for that
https://github.com/SwiftyJSON/SwiftyJSON
Add this library to your project.
After adding it, now review the below code:-
let json = JSON(data: jsonData!)
for (index, subjson): (String, JSON) in json{
let value = subjson["key"].stringValue
}
Upvotes: 0