ssowri1
ssowri1

Reputation: 1317

Swift 3.0 - Read .JSON file from XCode bundle

I've kept these .plist and .json files in my project. I could read the .plist file from Xcode. Although couldn't read .json file on Swift 3.0. I have used the below code snippet for getting this. but couldn't do that. Is it possible to get the data from .json file? kindly share your suggestions.

Could fetch the PLIST file

let plistFile = Bundle.main.path(forResource: "content", ofType: "plist")
let dictPlist = NSDictionary(contentsOfFile: plistFile!)
print(dictPlist ?? "")

Couldn't Fetch the JSON file

    if let filepath = Bundle.main.path(forResource: "fruits", ofType: "json") {
        do {
            let contents = try String(contentsOfFile: filepath)
            print(contents)
        } catch {
            print("Fetched")
        }
    } else {
        print("not found")
    }

Upvotes: 0

Views: 2313

Answers (2)

Vikram Kumar
Vikram Kumar

Reputation: 229

Swift 5 Solution

guard let fileUrl = Bundle.main.url(forResource: "fruits", withExtension: "json") else {
    return
}

do {
    let jsonData = try Data(contentsOf: fileUrl, options: .alwaysMapped)
    let dict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? Dictionary<AnyHashable, Any>
    print(dict?["json_key"])
} catch {
    print("Error:", error)
}

Upvotes: 1

dnlkng
dnlkng

Reputation: 839

Swift 4 Solution

If the filepath was properly found, there could be an problem with the file encoding. You should explicitly provide the actual encoding of the json file.

To check the encoding of your file, open the file in XCode and have a look at file inspector at the right side bar:

Encoding of the file

if let filePath = Bundle.main.path(forResource: "data", ofType: "json"),
   let data = NSData(contentsOfFile: filePath) {
  do {

    // here you have your json parsed as string:
    let jsonString = try? String(contentsOfFile: filePath, encoding: String.Encoding.utf8)

    // but it is better to use the type data instead:
    let jsonData = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)
  }
  catch {
    //Handle error
  }
}

Upvotes: 2

Related Questions