0

I'm trying to get data using JSON ad there is a null value causes crash.

let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//code error bad instruction

NSLog("Success: %ld", success);

how can I turn null to zero?

Sulthan
  • 128,090
  • 22
  • 218
  • 270
vahidgr
  • 81
  • 10

1 Answers1

0
let success = (jsonData["success"] as? NSInteger) ?? 0

step by step:

  1. get the value jsonData["success"] (please, don't use valueForKey, it does something completely different)
  2. as? NSInteger - try to cast it to NSInteger or return nil if it's not a number (in this case, it's a NSNull instance)
  3. ?? 0 - if nil, use a default value of zero
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • thank you for your answer but this line has beed activated: `if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as! NSString } else { error_msg = "Unknown Error" }` – vahidgr Mar 19 '16 at 16:05
  • @VahidGR That line does not even appear in the question. If you have more bugs, please, try to fix them first by yourself and then possibly ask another question. Don't forget to also include the JSON data you are trying to parse. – Sulthan Mar 19 '16 at 16:10