【问题标题】:if condition in json response in swift iosif条件在swift ios中的json响应中
【发布时间】:2017-02-13 10:23:43
【问题描述】:

如果服务器响应是 (result = "Account Exists") 那么我可以做点什么。但是当我比较结果时,它给出了一个错误,“二进制运算符'=='不能应用于'Any'和'String'类型的操作数”。

let dataTask = session.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in

        do
        {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary

            print("JSON : \(json)")

            if let dataDic = json.value(forKey: "data")
           {
            print("dataDic: \(dataDic)")

            if let Result = (dataDic as AnyObject).value(forKey: "Result")
            {
            print("Result: \(Result)")

                if (Result ("Account Exists")) == 0
                {
                    //... DO Something
                }
            }
            }
        }
        catch
        {
            print("Catch exception")
        }
    })
    dataTask.resume()
}

【问题讨论】:

  • 我得到“无法将 '__NSSingleObjectArrayI' (0x10d935d60) 类型的值转换为 'NSString' (0x10cb46c40)”@EICaptainv2.0
  • 您的回复如何?
  • 这是 JSON{ data = ( { Result = "Unauthorized Access"; } ); }
  • 当 Result = "Unauthorized Access" 我想做点什么

标签: ios iphone json swift


【解决方案1】:

以纯粹的快速方式..您的“数据”是一个数组,顶级 json 是字典

   do
    {
       let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]

       if let data = json["data"] as? [[String:String]] {
           if let resultString = data.first?["Result"] as? String{
               if resultString == "Account Exists"{
                   //... DO Something
               }
               else if resultString == "Unauthorized Access" {
                   //... DO Something
               }
           }
       }
    }
    catch{
        print("Catch exception")
    }

【讨论】:

  • 它有效。谢谢@EICaptainv2.0
  • 很高兴它有帮助..快乐 2 帮助你 :)
【解决方案2】:

请在您的代码下方更新并检查它

 if (Result ("Account Exists") as! String) == "0"
 {
         //... DO Something
 }

【讨论】:

  • 我收到此错误“无法调用非函数类型'String'的值”@Sunil prajapati
【解决方案3】:

如果你的Result是一个字符串,你需要相应地解包然后比较,你可以在解包的同时实现比较,你可以做类似的事情

 if let Result = (dataDic as AnyObject).value(forKey: "Result") as? String, Result == "Unauthorized Access"
{
    print("Result: \(Result)")
  // DO whatever you want here in case of Unauthorised access
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多