swift3.0中的Json解析
这是我在Swift中解析Jason的代码:swift3.0中的Json解析,swift3,Swift3,这是我在Swift中解析Jason的代码: static func POST(url: String, parameters: NSDictionary, completionBlock: @escaping CompletionBlock){ let todoEndpoint: String = Webservices.Base_Url.appending(url) guard let url = NSURL(string: todoEndpoint) e
static func POST(url: String, parameters: NSDictionary, completionBlock: @escaping CompletionBlock){
let todoEndpoint: String = Webservices.Base_Url.appending(url)
guard let url = NSURL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
var request = URLRequest(url: url as URL)
//var request = URLRequest(url: NSURL(string: todosEndpoint)! as URL)
let session = URLSession.shared
request.httpMethod = "POST"
var err: NSError?
let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
request.httpBody = jsonData
request.addValue("application/x-www-form-urlencoded;charset=UTF-8 ", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
guard error == nil else {
print("error calling POST on /todos/1")
print(error)
return
}
// make sure we got data
guard let dataTemp = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: dataTemp, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo, let's just print it to prove we can access it
print("The todo is: " , todo)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
} catch {
print("error trying to convert data to JSON")
return
}
})
task.resume()
}
我在分析jason时得到:
错误表达式生成错误:错误:执行被中断,
原因:EXC\u访问错误(代码=1,地址=0x0)。这一过程已经完成
返回到表达式计算前的状态
出什么问题了?您能识别出它崩溃的线路吗?最有可能的是jsonData为零