Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Handle json null values in Swift

I am playing With JSON for last two days and facing alot of curious problems and thanks to stack overflow it helps me. This is JSON featured key has two types of String 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 can't found solution, you answer will be appreciated.

like image 654
AyAz Avatar asked Jun 03 '16 05:06

AyAz


People also ask

How do you handle null values in Codable Swift?

A null value (no string) is treated as nil by default so the decoding is supposed to succeed if the property is optional. By the way: You can omit the CodingKeys. If the name of the properties are the same as the keys you don't need explicit CodingsKeys .

Can you send null in JSON?

If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.

How do I check if a JSON is null?

To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value. 2) The null value itself.


2 Answers

Try This

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 will convert null value to nil and wont' cause crash in your app.

You can also use as?

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

Thanks.

like image 125
Chatar Veer Suthar Avatar answered Sep 21 '22 08:09

Chatar Veer Suthar


Here is a working code, type cast operator(as?) will do the trick here. Null will not be typecasted into String, so the execution will go to failure block.

if let featured = dict["featured"] as? String {
    print("Success")
}
else {
    print("Failure")
}
like image 36
Paramasivan Samuttiram Avatar answered Sep 22 '22 08:09

Paramasivan Samuttiram