Reputation: 3002
How can I serialize JSON in swift? I am trying to serialize using this method, however it is causing EXC_BAD_INSTRUCTION. For downloading JSON data, I am using NSURLConnection.
var sJson : NSDictionary = NSJSONSerialization.JSONObjectWithData(nsMutData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
How can I solve it?
Regards
Upvotes: 2
Views: 19487
Reputation: 11336
In Swift 4+, JSON Serialization is best done by utilizing the Decodable
and Encodable
protocols.
Apple docs about encoding/decoding (or serializing/deserializing) custom types
Download sample code from Apple on this page
There is also a detailed tutorial by Ray Wenderlich: Encoding and Decoding in Swift
Upvotes: 0
Reputation: 5241
This is the swift 2.0 way
let path : String = NSBundle.mainBundle().pathForResource("jsonDict", ofType: "JSON")!;
let data : NSData = NSData(contentsOfFile: path)!;
var jsonDictionary : NSDictionary
do {
jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSDictionary
} catch {
print(error)
}
Upvotes: 3
Reputation: 22236
Your root-level data is an array of dictionaries -- not a dictionary; therefore replace your line with:
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray
I tested it and it now works with your data.
Here's how I tested it after having created a "json.txt" file in my project:
var filePath = NSBundle.mainBundle().pathForResource("json", ofType:"txt")
var nsMutData = NSData(contentsOfFile:filePath)
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray
Upvotes: 12