使用 swift 中的方法 POST,JSONSerialization.jsonObject 的响应为零 3
Response of JSONSerialization.jsonObject is nil with the method POST in swift 3
这是我想做的事情的示例,但是行 if let json = try JSONSerialization.jsonObject(with: data) as? [String: String]
是 false
因为 JSONSerialization.jsonObject
的 return 是 nil
func parser(lbl: UILabel){
let postString = "xxx=xxx&xxxx=xxxx==&xxxxx=xxxxx&xxxxxx=xxxxxx&xx=xx"
let url = URL(string: "http://xxxxxxxxxx.com/xxxxxx/xxxxx/xxxxxx.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
lbl.text = "error";
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
DispatchQueue.main.async {
let error = Int(json["success"]!)
let message = json["message"]
lbl.text = message
}
}
} catch let parseError {
print("error to parse: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("response`enter code here` : \(responseString!)")
}
}
task.resume()
}
试试这个:
var resultFromServer: Any?
resultFromServer = try JSONSerialization.jsonObject(with: data!, options: [])
这应该会为您提供 resultFromServer 作为 Any?
类型,只需根据您获得的响应(数组或字典)进行检查和类型转换。
喜欢
if let respdict = resultFromServer as? [String : Any] {
//respone in dictionary format
}
else if let respArr = resultFromServer as? [Any]{
//response is array type
}
else if let stringRespt = String(data: data, encoding: .utf8){
//resp is string
}
只需根据您的 JSON
进行更改
这是我想做的事情的示例,但是行 if let json = try JSONSerialization.jsonObject(with: data) as? [String: String]
是 false
因为 JSONSerialization.jsonObject
的 return 是 nil
func parser(lbl: UILabel){
let postString = "xxx=xxx&xxxx=xxxx==&xxxxx=xxxxx&xxxxxx=xxxxxx&xx=xx"
let url = URL(string: "http://xxxxxxxxxx.com/xxxxxx/xxxxx/xxxxxx.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
lbl.text = "error";
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
DispatchQueue.main.async {
let error = Int(json["success"]!)
let message = json["message"]
lbl.text = message
}
}
} catch let parseError {
print("error to parse: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("response`enter code here` : \(responseString!)")
}
}
task.resume()
}
试试这个:
var resultFromServer: Any?
resultFromServer = try JSONSerialization.jsonObject(with: data!, options: [])
这应该会为您提供 resultFromServer 作为 Any?
类型,只需根据您获得的响应(数组或字典)进行检查和类型转换。
喜欢
if let respdict = resultFromServer as? [String : Any] {
//respone in dictionary format
}
else if let respArr = resultFromServer as? [Any]{
//response is array type
}
else if let stringRespt = String(data: data, encoding: .utf8){
//resp is string
}
只需根据您的 JSON
进行更改