如何在Swift中检查JSON是否为空?

12

我目前正在开发一个应用程序,它返回以下格式的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语句处呢?

提前感谢您。


@MartinR 如果我尝试以下代码 if (dict["outcome_status"] as NSString != "") 它仍然会崩溃。 - chirag90
6个回答

27

试试这样做:

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


1
谢谢,这个非常有效,应用程序现在不会崩溃了。 - chirag90
太棒了...我根本没有处理悲伤路径,我的应用程序在悲伤路径上崩溃了 :/ - Chris Allinson
这个例子适用于字符串...但对于其他类型不起作用。我认为最好的解决方案是@NunoFerro https://dev59.com/V14b5IYBdhLWcg3wXAV1#37468020 - Jose Pose S
@JosePoseS 你需要注意代码中的类型转换运算符(as?),它会尝试将JSON内容转换为字符串(如果无法转换则返回nil)。因此,如果你的JSON内容不是字符串,你需要更改类型。 - Vagner
@Vagner,你需要更加关注标题问题。“如何在Swift中检查Json是否为空?”而不是字符串或其他类型。我也点赞了,因为这一点并没有错。 - Jose Pose S
@JosePoseS 是的,你说得没错...但也不完全正确...你需要看到问题标题之外的东西。我来这里并不是为了“字面上”回答问题,而是为了帮助人们解决问题。显然,在问题正文中,OP 需要两件事:1-检查键是否存在,2-将内容转换为特定类型,if let 语句可以实现这一点。 - Vagner

17
if ((nullObject as? NSNull) == nil)  {
        ...
       }

10

如果您正在使用Alamofire和JSONSubscriptType,请使用以下代码:

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

1
尝试使用相应的Swift类来对应以下Objective C类,
dict["outcome_status"] != [NSNull null]

0
您可以像这样检查json是否为空:
if let data = response["data"].dictionary {
    // do something
}
else {
    // do something
}

0
如果您正在使用SwiftyJSON,只需检查对象上的.isEmpty()以确认它是否为空。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接