chi*_*g90 9 xcode json ios swift
我目前正在开发一个应用程序,它以下列格式返回json
"location_subtype"="somevalue"; "location_type"=强制; month ="2015-01"; "outcome_status"= {category ="somevalue"; date ="somevalue"; };
如果"outcome_status"具有值,则显示类别和日期,但是如果"outcome_value"没有任何值(在大多数情况下),则显示如下
"location_subtype"="somevalue"; "location_type"=强制; month ="2015-01"; "outcome_status"=""; "persistent_id"="";
问题是我如何检查outcome_status的值是否不是"null"?
我已经尝试了以下方法将类别和日期存储到标签中,但它会遇到错误,第一个if语句应该检查该值是否为null,如果它不是转到下一个if语句.然而,它继续下一个if语句,我得到以下错误
线程1:EXC_BAD_ACCESS(代码= 2,地址= 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果我删除第一个if语句,它只会在"outcome_status"="null"时崩溃,并且如果"outcome_status"中有一些值则完全正常
我需要做什么,如果值为null,它会在1st if语句处停止?
先感谢您.
Vag*_*ner 24
尝试这样的事情:
SWIFT代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这是与Json合作的安全方式.
如果您使用的是 Alamofire 和 JSONSubscriptType,请使用:
if !(parsedJSON["someKey"] == JSON.null) {
//do your stuff
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27716 次 |
| 最近记录: |