Reading JSON file using Swift 3

I have a JSON file called point.json and a read function like:

private func readJson() { let file = Bundle.main.path(forResource: "points", ofType: "json") let data = try? Data(contentsOf: URL(fileURLWithPath: file!)) let jsonData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any] print(jsonData) } 

It doesn't work, any help?

+32
json swift3
Nov 05 '16 at 13:28
source share
2 answers

Your problem is that you are forcibly unwrapping the values, and in case of an error you cannot know where it came from.

Instead, you should handle errors and safely deploy your options.

And as @vadian correctly points out in his comment, you should use Bundle.main.url .

 private func readJson() { do { if let file = Bundle.main.url(forResource: "points", withExtension: "json") { let data = try Data(contentsOf: file) let json = try JSONSerialization.jsonObject(with: data, options: []) if let object = json as? [String: Any] { // json is a dictionary print(object) } else if let object = json as? [Any] { // json is an array print(object) } else { print("JSON is invalid") } } else { print("no file") } } catch { print(error.localizedDescription) } } 

When coding in Swift usually ! is the smell of code. Of course, there are exceptions (IBOutlets and others), but try not to use a power scan with ! independently and always deploy safely.

+95
Nov 05 '16 at 13:34
source share

The Swift 5 / iOS 12.3 code below shows a possible rewrite of your method, avoiding the forced deployment of optional values ​​and accurately handling possible errors:

 import Foundation func readJson() { // Get url for file guard let fileUrl = Bundle.main.url(forResource: "Data", withExtension: "json") else { print("File could not be located at the given url") return } do { // Get data from file let data = try Data(contentsOf: fileUrl) // Decode data to a Dictionary<String, Any> object guard let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { print("Could not cast JSON content as a Dictionary<String, Any>") return } // Print result print(dictionary) } catch { // Print error if something went wrong print("Error: \(error)") } } 
+2
Oct. 20 '18 at 12:41
source share



All Articles