【问题标题】:Cannot convert jsonArray element to integer无法将 jsonArray 元素转换为整数
【发布时间】:2015-10-05 16:34:16
【问题描述】:
do{
    let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
    let arrayJSON = resultJSON as! NSArray

    let success:NSInteger = arrayJSON["success"] as! NSInteger

    if (success == 1 ) ....

json 数据是来自服务器的响应,我正在尝试将其转换为整数,但出现对话错误。

【问题讨论】:

  • 在做任何事情之前,你能打印一下数据吗?我向您展示的示例预计响应是 json 数组。让我们看看您的回复以便正确解析它
  • 数据 =
  • print(response) 生成什么?
  • { URL: myurl } { 状态码: 200, headers { "Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0 , 预检=0";连接=“保持活动”; “内容类型”=“应用程序/json”;日期 =“格林威治标准时间 2015 年 10 月 5 日星期一 16:46:50”; Expires = "1981 年 11 月 19 日星期四 08:52:00 GMT"; “保活”=“超时=10,最大值=150”; Pragma = "无缓存";服务器=阿帕奇; “设置 Cookie”=“PHPSESSID=bd51710ab7f881ff59927393f0d6f050;路径=/”; “传输编码” = 身份; "X-Powered-By" = "PHP/5.3.29"; } }
  • 也请print(data!) 告诉我结果

标签: ios swift swift2


【解决方案1】:

这是一个工作示例(在我的机器上测试)

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if let error = error {
                print(error)
            }
            if let data = data{
                print("data =\(data)")
                do{
                let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                let resultDictionary = resultJSON as? NSDictionary

                    let success = resultDictionary!["success"]!
                    let successInteger = success as! Int
                    print("success = \(success)")
                    if successInteger == 1 {
                        print("yes")
                    }else{
                        print("no")
                    }
                }catch _{
                    print("Received not-well-formatted JSON")
            }

            }
            if let response = response {
                print("url = \(response.URL!)")
                print("response = \(response)")
                let httpResponse = response as! NSHTTPURLResponse
                print("response code = \(httpResponse.statusCode)")
            }



        })
        task.resume()

响应在哪里:

{ "error_message" : "No User", "success" : 0}

注意

您说您的服务器响应为:

{ "error_message" = "No User"; success = 0; } 

这是不是一个有效的 json,你应该更正它以匹配我给你的 json

【讨论】:

  • 当我这样做时 -> if(success == 1) {} 我收到此错误 此应用程序正在从后台线程修改自动布局引擎,这可能导致引擎损坏和奇怪的崩溃。这将在未来的版本中导致异常。
  • @RULE101 好的,我正在创建一个真正的 REST Web 服务来测试您的情况,只需 5 分钟,我就完成了测试
  • @RULE101 现在请检查我的答案
  • 服务器响应有效的 JSON 但 xcode 调试器显示错误;这很奇怪
【解决方案2】:

您将resultJSON 转换为NSArray,但随后您尝试通过下标“成功”将其用作字典。

如果响应是字典,则将结果转换为字典:

let result = resultJSON as! NSDictionary
let success = result["success"] as! NSInteger

如果响应是字典数组,则在下标之前先选择其中一项。

let arrayJSON = resultJSON as! NSArray
let success = arrayJSON[0]["success"] as! NSInteger

注意:如果可能,最好使用 Swift 的类型化数组和字典,而不是 Foundation 的 NSArray 和 NSDictionary。此外,您应该避免使用! 强制转换,最好使用if let ... = ... as? ... 或任何其他机制安全地打开选项。

更新

这是一个例子:

do {
    let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())

    var success = 0

    if let dictJSON = resultJSON as? [String:AnyObject] {
        if let successInteger = dictJSON["success"] as? Int {
            success = successInteger
        } else {
            print("no 'success' key in the dictionary, or 'success' was not compatible with Int")
        }
    } else {
        print("unknown JSON problem")
    }

    if success == 1 {
        // yay!
    } else {
        // nope
    }

在这个例子中,我使用的是 Swift 字典 [String:AnyObject] 而不是 NSDictionary,我使用的是 Swift 整数 Int 而不是 Foundation 的 NSInteger。我也在使用if let 进行类型转换,而不是强制。

【讨论】:

  • 我是 swift 新手。谢谢你。你能举一些例子来解释你的笔记吗?
  • 如果成功 == 1 后无法使用 dictJSON["userID"] 我使用未解析的标识符
  • 这是一个新的不同的错误,如果你到达那里,这意味着我已经解决了你原来的问题。 :) 当然dictJSON 后面没有解决,因为它是if let dictJSON ... 的本地,它只存在于这个分支中。要么在这个分支中使用它,要么将结果分配给另一个变量以供以后使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多