user2498079
user2498079

Reputation: 3002

JSON Serialization in Swift iOS

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

Answers (3)

Josh Withee
Josh Withee

Reputation: 11336

In Swift 4+, JSON Serialization is best done by utilizing the Decodable and Encodable protocols.

There is also a detailed tutorial by Ray Wenderlich: Encoding and Decoding in Swift

Upvotes: 0

Mohammad Sadiq
Mohammad Sadiq

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

Jean Le Moignan
Jean Le Moignan

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

Related Questions