【问题标题】:"NSArray is not convertible to NSData" error“NSArray 不能转换为 NSData”错误
【发布时间】:2015-09-04 10:25:19
【问题描述】:

我在 iOS 中使用带有 swift 的 socket.io。我必须阅读一个json。

我的 Json:

{
    "result": [
        {
            "id": 1,
            "username": "testuser1",
            "password": "testuser1",
            "phone": "+905557664823"
        },
        {
            "id": 2,
            "username": "testuser2",
            "password": "testuser2",
            "phone": "+905555648584"
        }
    ]
}

我的代码:

    self.socket.on("contactList") {data, ack in
        let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>
        let results: NSArray = jsonResult["result"] as! NSArray
    }

但我收到以下编译器错误:

'NSArray' 不能转换为 'NSData'

我该如何解决?

Ps:data 变量包含 json。

【问题讨论】:

标签: ios json swift socket.io


【解决方案1】:

试试这个:

let resultData = (data.firstObject as! String).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(resultData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>
let results: NSArray = jsonResult["result"] as! NSArray

【讨论】:

  • data 更改为 resultData
  • 你能解释一下第一行吗?它在做什么?
  • data.firstObject 是这样的 JSON 字符串:"{"result":[{"id":1,"username":"testuser1","password":"testuser1","phone":"+905557664823"}]}"。由于某种原因,该库将数据作为 NSArray 返回给您,例如 ["{result:xxxx}"],因此您必须获取第一个对象并转换为 NSData,然后您可以调用 NSJSONSerialization.JSONObjectWithData
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多