15

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.

2
  • Is it causing crash? Jun 3, 2016 at 5:18
  • yes while in storing coredata
    – AyAz
    Jun 3, 2016 at 5:19

6 Answers 6

46

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
  • 10000000 up Votes for this answer. Oct 11, 2018 at 9:36
  • This is awesome, thanks! If you are using Alamofire and SwiftyJSON, you will have to force downcast as AnyObject for it to work. =D my example looks as such: object["feature"] : JSON my null check looks like: if nullToNil(value: object["feature"] as AnyObject) != nill { // do something }
    – llamacorn
    Jul 9, 2019 at 23:06
6

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

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

2

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);
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.