How To Handle json null values in Swift

2020-02-25 07:28发布

问题:

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.

回答1:

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.



回答2:

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")
}


回答3:

Try this!

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


回答4:

Optional chaining with if let or its counterpart guard let is the way to go. All three steps combined (missing, 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 optional chaining check out documentation



回答5:

Hi you can use below function to remove null to empty string and prevent crashes

func removeNullFromDict (dict : NSMutableDictionary) -> NSMutableDictionary
{
    let dic = dict;

    for (key, value) in dict {

        let val : NSObject = value as! NSObject;
        if(val.isEqual(NSNull()))
        {
            dic.setValue("", forKey: (key as? String)!)
        }
        else
        {
            dic.setValue(value, forKey: key as! String)
        }

    }

    return dic;
}

and before giving dict to any method call function in below way

let newdict = self.removeNullFromDict(dict: dict);


回答6:

i did a static func to convert value from json to optional String.

class Tools{

    static func setOptionalStr(value : Any?) -> String?{
        guard let string = value as! String?, !string.isEmpty else {
            return nil
        }
        return  value as? String
    }
}

In my controller

let urlStats: String? = Tools.setOptionalStr(value: json["UrlStats"])

i'm open to your feedback