How to handle json null values ​​in Swift

I have been playing with JSON for the last two days and am facing a lot of interesting problems and thanks to the stack overflow, this helps me. it is JSON featured, has a tow type of String Type values.

"featured":"1" 

or

 "featured": null, 

I tried a lot to handle this, but failed

 step 1) if dict.objectForKey("featured") as? String != nil { featured = dict.objectForKey("featured") as? String } 

step 2)

  let null = NSNull() if dict.objectForKey("featured") as? String != null { featured = dict.objectForKey("featured") as? String } 

step 3)

  if dict.objectForKey("featured") as? String != "" { featured = dict.objectForKey("featured") as? String } 

but unfortunately cannot find a solution, you will answer.

+7
json null swift core-data
source share
4 answers

try it

 func nullToNil(value : AnyObject?) -> AnyObject? { if value is NSNull { return nil } else { return value } } object.feature = nullToNil(dict["feature"]) 

Here you can use this method, which converts null to nil and will not crash in your application.

You can also use how?

 object.feature = dict["feature"] as? NSNumber 

Thanks.

+16
source share

Here is the working code, an operator like cast (as?) Will do the trick here. Null will not be entered into String, so execution will be sent to the block of failures.

 if let featured = dict["featured"] as? String { print("Success") } else { print("Failure") } 
+5
source share

An additional binding to if let or its guard let counterpart is the path. All three steps are combined (absent, wrong type - NSNull too, empty string):

 guard let featured = dict.objectForKey("featured") as? String where !value.isEmpty else { print("featured has wrong value") } // do what you need to do with featured 

If you want to know more about the additional chain check the documentation.

+3
source share

Try it!

 if let demoQuestion = dict.objectForKey("featured"){ let getValue: String = demoQuestion as! String } else { print("JSON is returning nil") } 
+2
source share

All Articles