gpt4 book ai didi

ios - 如何快速检查 JSON 是否为空?

转载 作者:IT王子 更新时间:2023-10-29 05:38:46 25 4
gpt4 key购买 nike

我目前正在开发一个以下列格式带回 json 的应用程序

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

如果“outcome_status”有值,它会显示类别和日期,但是如果“outcome_value”没有任何值(在大多数情况下),则显示如下

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

问题是如何检查 outcome_status 的值是否不为“null”?

我尝试了以下方法将类别和日期存储到标签中,但它遇到了错误,第一个 if 语句应该检查值是否不为空,如果不为 null 则转到下一个 if 语句。但是它继续到下一个 if 语句,我得到以下错误

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 语句,它只会在“outcome_status”=“null”时崩溃,并且在“outcome_status”中有一些值时工作得很好

如果值为 = null,我需要做什么才能在第一个 if 语句处停止?

提前谢谢你。

最佳答案

尝试这样的事情:

快速代码:

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 的安全方式。

关于ios - 如何快速检查 JSON 是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29264449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com