我有来自socket io库的响应,有这样的响应
socket.on("response-names") { data, ack in
print(data)
}
可以打印这个,
[{
"person": [{
"_id":"56512323212132",
"name":"John Smith",
"id":"0000001",
"geolocation":{
"latitude":5.12312323443,
"longitude":101.12312464564354
}
}]
}]
你们如何在swift中访问名称,id和地理位置(lat,long)?,
据我所知,数据是NSArray。但访问是数据[0]将产生零。但我可以做data.count,它将以1返回。
谢谢
答案 0 :(得分:1)
最后我解决了这个问题,仅供其他人参考。在解析之前,您似乎需要知道类型。并打印检查。
并且调试代码确实很有用,像NSCFArray
之类的东西意味着您的数据为NSArray
,并尝试从中读取。
let dataArray = data as NSArray
let dataString = dataArray[0] as! String
let dataNewNow = dataString.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try NSJSONSerialization.JSONObjectWithData(dataNewNow, options: []) as! [String: AnyObject]
let str = json["person"] as! NSArray
let str2 = str[0] as! NSDictionary
let personName = str2["name"] as! String
let personId = str2["id"] as! String
let personGeoLocation = str2["geolocation"] as! NSDictionary
let personLatitude = personGeoLocation["latitude"] as! NSNumber
let personLongitude = personGeoLocation["longitude"] as! NSNumber
print("personName =", personName)
print("personID =", personId)
print("Person Latitude =", personLatitude)
print("Person Longitude =", personLongitude)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
答案 1 :(得分:0)
在我的情况下,这工作
let dataArray = data as NSArray
let dataString = dataArray[0] as! String
let dataNewNow = dataString.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: dataNewNow, options: []) as! [String: AnyObject]
let nMsgType = json["msg_type"] as! String
print(nMsgType)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}