我目前正在开发一个应用程序,它可以返回 json,格式如下
“location_subtype”=“某个值”;
“位置类型”=强制;
月份=“2015-01”;
“结果状态”= {
类别=“某个值”;
日期=“某个值”;
};
如果“outcome_status”具有值,则显示类别和日期,但是如果“outcome_value”没有任何值(在大多数情况下),则显示如下
“location_subtype”=“某个值”;
“位置类型”=强制;
月份=“2015-01”;
“结果状态”=“”;
“持久ID”=“”;
问题是我如何检查outcome_status 的值是否不为“null”?
我已尝试以下方法将类别和日期存储到标签中,但遇到错误,第一个 if 语句应检查该值是否不为空,如果不是则转到下一个 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
}
}
如果我删除第一个 if 语句,它只会在“outcome_status”=“null”时崩溃,并且如果“outcome_status”中有一些值则工作得很好
如果值为 = null,我需要做什么才能在第一个 if 语句处停止?
先感谢您。
尝试这样的事情:
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
}
}
这是使用 Json 的安全方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)