How to check if JSON is null in swift?

前端 未结 5 1712
Happy的楠姐
Happy的楠姐 2021-02-20 14:47

I am currently working on an app which brings back json, in the following format

\"location_subtype\" = \"somevalue\"; \"location_type\" = Force;

相关标签:
5条回答
  • 2021-02-20 15:07

    Try corresponding Swift class to following Objective C class,

    dict["outcome_status"] != [NSNull null]
    
    0 讨论(0)
  • 2021-02-20 15:09

    Try something like this:

    Swift code:

    if let outcome = dict["outcome_status"] as? NSDictionary {
        //Now you know that you received a dictionary(another json doc) and is not 'nil'
        //'outcome' is only valid inside this if statement
    
        if let category = outcome["category"] as? String {
            //Here you received string 'category'
            outcomeStatusLabel.text = category
            outcomeStatusLabel.font = UIFont.systemFontOfSize(14.0)
            outcomeStatusLabel.numberOfLines = 0
        }
    
        if let date = outcome["date"] as? String {
            //Here you received string 'date'
            outcomeDateLabel.text = date
            outcomeDateLabel.font = UIFont.systemFontOfSize(14.0)
            outcomeDateLabel.numberOfLines = 0
        }
    }
    

    This is a safe way to work with Json.

    0 讨论(0)
  • 2021-02-20 15:11

    in case you are using Alamofire and JSONSubscriptType use this:

    if !(parsedJSON["someKey"] == JSON.null) {
    //do your stuff 
    }
    
    0 讨论(0)
  • 2021-02-20 15:22

    If you're using SwiftyJSON, just check .isEmpty() on the object to confirm if it's empty.

    0 讨论(0)
  • 2021-02-20 15:23
    if ((nullObject as? NSNull) == nil)  {
            ...
           }
    
    0 讨论(0)
提交回复
热议问题