使用SwiftyJSON解析Alamofire JSON结果
我不使用SwiftyJSON填充表视图,它不是解析Alamofire JSON结果使用SwiftyJSON解析Alamofire JSON结果,json,swift,xcode,alamofire,swifty-json,Json,Swift,Xcode,Alamofire,Swifty Json,我不使用SwiftyJSON填充表视图,它不是解析Alamofire JSON结果 let getRouteURL = "http://example.com/api/Trafi/GetRoute/" Alamofire.request(getRouteURL, method: HTTPMethod.post, parameters: param, encoding: JSONEncoding.default, headers:nil).responseJSON{ response in
let getRouteURL = "http://example.com/api/Trafi/GetRoute/"
Alamofire.request(getRouteURL, method: HTTPMethod.post, parameters: param, encoding: JSONEncoding.default, headers:nil).responseJSON{ response in
if let result = response.result.value {
if let JSON = try? JSON(result){
if let RoutesArr = JSON["Routes"].arrayObject{
self.routes = RoutesArr as! [[String : AnyObject]]
self.routeTable.reloadData()
}
}
}
}
数据示例
编辑:此代码正在工作,但错误原因是我的web服务错误。谢谢你的帮助 我只是这样做:
let request = Alamofire.request(url, method: method, parameters: params, encoding: URLEncoding.default, headers: httpHeaders).validate()
request.responseJSON { response in
switch response.result {
case .success(let json):
let jsonObject = JSON(json)
//Use jsonObject
....
}
}
如果我没记错的话,这个模式来自Alamofire GitHub示例。我看看能不能找到链接
我认为我对这种模式的使用可能源于。这就是我在swift3上使用SwiftyJSON处理JSON的方式
// handle data
if let value = response.result.value {
let json = JSON(value)
for(_, location): (String, JSON) in json{
let pendingLocation = PendingLocation(_id: location["_id"].stringValue, userId: location["userID"].stringValue, name: location["name"].stringValue)
self.pendingLocations.append(pendingLocation)
self.tableView.reloadData()
}
}
请求json请求时,将内容类型头设置为application/json,如下所示:
let headers = [
"Content-Type" : "application/json; charset=UTF-8"
]
let getRouteURL = "http://example.com/api/Trafi/GetRoute/"
Alamofire.request(getRouteURL,
method: HTTPMethod.post,
parameters: param,
encoding: JSONEncoding.default,
headers:headers).responseJSON{ response in
if let result = response.result.value {
if let JSON = try? JSON(result){
if let RoutesArr = JSON["Routes"].arrayObject{
self.routes = RoutesArr as! [[String : AnyObject]]
self.routeTable.reloadData()
}
}
}
}
不起作用,请查看我的示例json数据。它的错误是Domain=NSCocoaErrorDomain Code=3840“JSON文本没有以数组或对象和允许未设置片段的选项开头。”UserInfo={NSDebugDescription=JSON文本没有以数组或对象和允许未设置片段的选项开头。}@ErenÖzkul,当服务不返回JSON时,通常会出现该错误。大多数情况下,这是因为我没有得到200HTTP响应。@JamesWebster我知道200HTTP响应,但问题在于“内容类型”。我修好了,谢谢你的帮助我必须用阿拉莫菲利亚对不起。这并不明显,但确实如此。我在请求时编辑并将内容类型设置为json。@EricAya不,只是响应数据不正确您是对的@Dory