chirag90 chirag90 - 6 months ago 22
JSON Question

How to check if Json is null in swift?

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


"location_subtype" = "somevalue";
"location_type" = Force;
month = "2015-01";
"outcome_status" = {
category = "somevalue";
date = "somevalue";
};


if the "outcome_status" has value it shows category and date however if the "outcome_value" does have any value(which is in most of the cases) it is shown as below


"location_subtype" = "somevalue";
"location_type" = Force;
month = "2015-01";
"outcome_status" = "";
"persistent_id" = "";


The question is how can i check if the value for outcome_status is not "null"?

i have tried the following to store the category and date into label but it runs into error, the first if statement should check if the value is not null and if it is not go to next if statement. However it continues to next if statement and i get the following error


Thread 1: EXC_BAD_ACCESS(code=2, address=0x102089600)


if (dict["outcome_status"] != nil)
{
if ((dict["outcome_status"]as NSDictionary)["category"] != nil)
{
outcomeStatusLabel.text = ((dict["outcome_status"]as NSDictionary)["category"] as NSString)
outcomeStatusLabel.font = UIFont.systemFontOfSize(14.0);
outcomeStatusLabel.numberOfLines = 0
}

if ((dict["outcome_status"]as NSDictionary)["date"] != nil)
{
outcomeDateLabel.text = ((dict["outcome_status"]as NSDictionary)["date"] as NSString)
outcomeDateLabel.font = UIFont.systemFontOfSize(14.0);
outcomeDateLabel.numberOfLines = 0
}
}


If i remove the 1st if statement it only crashes when "outcome_status" = "null" and works perfectly fine if there some value in "outcome_status"

What do i need to do so it stops at 1st if statement if the value is = null?

Thank you in advance.

Answer

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.