emabusi
emabusi

Reputation: 63

JSON data serialization in Swift

I am new to Xcode and Swift, and I am trying to serialize JSON data from a url using the code below and get the error

'NSJSONReadingOptions' is not convertible to 'NSJSONWritingOptions'

on the line

var jsonResult = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONReadingOptions.MutableContainers, error: nil)!

I cannot see my error, from online sources others use the same code and its works?

let task = session.dataTaskWithURL(loginUrl!, completionHandler: { (data, response, error) -> Void in
    if error != nil {
    }else {
        var jsonResult = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONReadingOptions.MutableContainers, error: nil)!
        println(jsonResult)
    }
})

task.resume();

Upvotes: 0

Views: 833

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Read the docs for dataWithJSONObject. The options parameter needs to be a value from the NSJSONWritingOptions enum, not the NSJSONReadingOptions enum.

But if your goal here is to convert an NSData object to an NSArray or NSDictionary, then the problem is that you are calling the wrong method. You want to use JSONObjectWithData, not dataWithJSONObject.

Upvotes: 1

Related Questions