我将输出作为字符串。但价值在关键&值
var buffer = Array<UInt8>(repeating: 0, count: 4096)
if ( aStream == inputStream){
while (inputStream.hasBytesAvailable){
let len = inputStream.read(&buffer, maxLength: buffer.count)
if(len > 0){
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
if (output != ""){
NSLog("server said: %@", output!)
receivingData = output as! String
delegate.socketReceiveData(responce: receivingData)
}
}
}
}
数据正在字典中,但对象在字符串中无法隐藏。
来自服务器的output = {“password": "12345", "method": "login", "mail_id": "abc@gmail.com"}
但输出是字符串
如何读取方法,密码等的值...
答案 0 :(得分:0)
这是一个JSON字符串"{"password": "12345", "method": "login", "mail_id": "abc@gmail.com"}"
您可以将其转换为字典,如下所示
let data = output!.data(using: String.Encoding.utf8, allowLossyConversion: false)
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
let dict = json as? [String: Any]
let method = dict?["method"]
print(method)
}
catch {
print(error)
}
你也可以试试
jsonObject(with stream: InputStream, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
方法并将输入流提供给它
尝试此代码
var buffer = Array<UInt8>(repeating: 0, count: 4096)
if ( aStream == inputStream){
while (inputStream.hasBytesAvailable){
let len = inputStream.read(&buffer, maxLength: buffer.count)
if(len > 0){
let data = Data(bytes: &buffer, count: buffer.count)
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
let dict = json as? [String: Any]
let method = dict?["method"]
print(method)
}
catch {
print(error)
}
// if (output != ""){
// NSLog("server said: %@", output!)
// receivingData = output as! String
// delegate.socketReceiveData(responce: receivingData)
// }
}
}
}
答案 1 :(得分:0)
使用此
let strf = "{\"name\":\"maan\"}"
let data = strf.data(using: String.Encoding.utf8)
do {
guard let toddo = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] else
{
print("error trying to convert data to JSON")
return
}
print(toddo);
}
catch {
print(error)
}