ios - 如何检查 JSON 响应的空条件?

标签 ios json swift

我正在尝试检查 json 响应的字典之一的空条件。但是当我检查条件时,我收到类似 “二元运算符‘==’无法应用于类型的操作数的错误'[String : Any]' 和 'JSON'”。我在 if !(chattt == JSON.null) 行收到此错误。如果有人帮助我解决这个问题,那就太好了。提前致谢。

 let acce:String = UserDefaults.standard.string(forKey: "access-tokenn")!
        print(acce)

        let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)","Content-Type":"application/X-Access-Token"]
        print((Constants.Chatlistsearch)+(idd))
        Alamofire.request((Constants.Chatlistsearch+idd), method: .get, encoding: URLEncoding.default, headers: headers).responseJSON {  response in
            switch response.result {
            case .success:
                //print(response)
                if response.result.value != nil{
                    var maindictionary = NSDictionary()
                    maindictionary = response.result.value as! NSDictionary
                  //  print(maindictionary)

                    var chat:Dictionary = maindictionary.value(forKey: "data") as! [String:Any]
                   // print(chat)

                    var chatt:Dictionary = chat["user"] as! [String:Any]
                   // print(chatt)

                    var chattt:Dictionary = chat["chat"] as! [String:Any]
                    print(chattt)



                    if !(chattt == JSON.null) {
                        let viewc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
                        self.navigationController?.pushViewController(viewc!, animated: true)
                    }else{
                        print("Find Action")
                    }


//                    self.data = [String(stringInterpolationSegment: chatt["unique_id"])]
//                    print(self.data)

                }
                break
            case .failure(let error):

                print(error)
            }
        }

    }

最佳答案

你可以这样做

if let chattt = chat["chat"] as? [String:Any] {
    //It's available. Execute further tasks
} else {
    //It's nil or chat["chat"] type is not dictionary.
}

您可以使用 guard 来完成。

guard let chattt = chat["chat"] as? [String:Any] else {
    //Using this, the further code will never execute as implemented force return here
    return
}

如果有任何问题,请告诉我。

关于ios - 如何检查 JSON 响应的空条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901402/

相关文章:

jquery - javascript jquery 将 mysql 中的 json 对象保存为字符串

ios - 使用 Computed 变量和 Snapkit 时 : No common superview between views

ios - 在 Xcode 单元测试中模拟网络连接? (可能与 AFNetworking 有关)

javascript - angularjs:将一个服务传递到另一个服务中?

json - 如何使用 swiftJson 和 Alamofire 解析 json 数据

swift - 可选的无主引用与 Swift 5.0 中的弱引用

ios - 除非我先调用 saveContext,否则核心数据中无法识别的选择器崩溃

swift - 将字符串转换为正确的日期

ios - 升级到 ios 13 时 xcodebuild 存档失败

ios - 如何阻止外部资源加载到 WKWebView 上?