我在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。
答案 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