" NSArray不能转换为NSData"错误

时间:2015-09-04 10:25:19

标签: ios json swift socket.io

我在iOS中使用带有swift的socket.io。我必须读一个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
    }

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

  

&#39; NSArray的&#39;不可转换为&#39; NSData&#39;

我该如何解决?

Ps:data变量包含json。

1 个答案:

答案 0 :(得分:2)

试试这个:

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