Gunja Patel
Gunja Patel

Reputation: 289

can not cast json data in swift

I successfully get json data but I have to cast that so that I can doing certain operation Here is json

var jsonResult : NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary

I have one object status,I have to check if it is 1 or not so I try this

if let status : NSNumber! = jsonResult["status"] as? NSNumber {
  //code
} 

for that but it will give me exception

fatal error: unexpectedly found nil while unwrapping an Optional value

so I found new solution

if jsonResult["status"] as! NSObject == 1{
//code 
}

It does not return any error but even json has this object and also it value is 1 but can not go to if clause I think some issue in casting but can not understood Here is json response

{
    message = success;
    status = 1;
}

Upvotes: 0

Views: 331

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Use safe unwrapping with if let instead of force unwrapping with !. Same for safely typecasting the result:

if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &err) as? NSDictionary {

    if let statusInt = jsonResult["status"] as? Int {

        println("Result is an Integer: \(statusInt)")

        if statusInt == 1 {

            // ...

        }

    } else if let statusString = jsonResult["status"] as? String {

        println("Result is a String: \(statusString)")

        if statusString == "1" {

            // ...

        }

    } else {

        // jsonResult["status"] could not be found

    }

} else {

    // error, couldn't decode JSON

}

Update for Swift 2.0

do {
    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
        if let statusInt = jsonResult["status"] as? Int {
            print("Result is an Integer: \(statusInt)")
            if statusInt == 1 {
                // ...
            }
        } else if let statusString = jsonResult["status"] as? String {
            print("Result is a String: \(statusString)")
            if statusString == "1" {
                // ...
            }
        } else {
            // jsonResult["status"] could not be found
        }
    } else {
        // error, couldn't decode JSON
    }
} catch let error as NSError {
    print(error)
}

Upvotes: 1

Related Questions