How to check if JSON is null in swift?

I am currently working on an application that returns json in the following format

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

if the value of "result_status" has a value, it shows the category and date, however, if the "result_value" has no value (which in most cases), it is shown below

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

The question is, how can I check if the value for result_status is "null"?

I tried the following to save the category and date in the label, but it was run in error, the first if statement should check if the value is null and if it does not go to the next if statement. However, it continues to follow if the operator and I get the following error:

Subject 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 delete the 1st operator, it only fails when "result_status" = "null", and works fine if there is any value in "result_status"

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

Thanks in advance.

+7
json ios xcode swift
source share
4 answers

Try something like this:

Quick 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.

+18
source share
 if ((nullObject as? NSNull) == nil) { ... } 
+6
source share

if you are using Alamofire and JSONSubscriptType, use this:

 if !(parsedJSON["someKey"] == JSON.null) { //do your stuff } 
+1
source share

Try the appropriate Swift class for the following Objective-C class,

 dict["outcome_status"] != [NSNull null] 
0
source share

All Articles