swift如何检查来自Json的NULL值

问题描述 投票:-1回答:4

我有一个休息api,我通过Json获取所有数据,然后将其放入IOS TableView。我的问题是有些数据在Json中作为NULL返回

"vote_status":null

我试图在swift中获取NULL值并将其更改为字符串“0”但是我很难这样做。到目前为止我有这个

  if var vote_status = Stream["vote_status"] as? String {
                                if (vote_status == (vote_status)[NSNull]) {
                                   vote_status = "0"
                                }
}

但是我得到了这个编译错误:

无法下标索引类型为'(NSNull).Type'的类型'String'的值(又名'NSNull.Type')

我这样做是因为nil和null似乎不起作用所以我不能这样做。

if (vote_status == nil) ...
json swift swift3 nsnull
4个回答
4
投票

您只需要有条件地将字典值转换为String并使用Nil Coalescing Operator ??在发生故障的情况下分配"0" null

let vote_status = Stream["vote_status"] as? String ?? "0"

1
投票

Swift 3.0

func checkNull(obj : AnyObject?) -> AnyObject? {
    if obj is NSNull {
        return nil
    } else {
        return value
    }
}

object.feature = checkNull(dict["feature"])

试试这个

vote_status is NSNull 

1
投票

你可以试试这个

func checkForNull(value:AnyObject) -> String
    {
        if(value as! NSObject == NSNull() || value as! String == "")
        {
           return " "
        }
        else
        {
            return value as! String
        }
    }

0
投票

尝试这样的事情:

if let category = Stream["vote_status"] as? String {
                        print(category)
                    } else {
                        print(category)
                    }
© www.soinside.com 2019 - 2024. All rights reserved.