首页 文章

ALAMOFIRE的JSON_encode

提问于
浏览
0

我有一个非常简单的Swift代码来检索JSON数据 . 但不知何故,它无法正常工作 .

Alamofire.request("*URL*").validate().responseJSON { response in
        print(response.result.value)
            if response.result.isSuccess {
               if let userList:[[String:Any]] = response.result.value as? [[String:Any]] {
                    for user:[String:Any] in userList {
                        if let userName = user["name"] as? String {
                            self._myList.append(User(name: userName, value: true))
                        }
                    }
                }
                self.tableView.reloadData()
            } else {
                print(response.result.error)
            }
    }

在执行期间,我在控制台中收到此错误消息:

可选(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain = NSCocoaErrorDomain Code = 3840)字符0周围的值无效 . “UserInfo = })))

调用Alamofire.request后的打印在控制台中显示“nil” .

我不明白的是,如果我使用.responseString而不是.responseJSON(但它只显示一个字符串),它会起作用 . 我真的需要使用.responseJSON,因为我需要解析结果 .

我在网络浏览器上显示的JSON也非常简单:

[{"name":"MrX","value":"0"}]

任何的想法 ?

米卡 .

1 回答

  • 0

    用这个

    import Alamofire
            import SwiftyJSON
    
            let baseURL: String = "http://baseURL.com"
            Alamofire.request(baseURL)
            .responseJSON { response in
    
                guard response.result.error == nil else {
                    // got an error in getting the data, need to handle it
                    print("error calling GET")
                    print(response.result.error!)
                    return
                }
    
                if let value = response.result.value {
    
                    let json = JSON(value) // JSON comes from SwiftyJSON
                    print(json) // to see the JSON response
                    let userName = json["name"].array // .array comes from SwiftyJSON
                    for items in userName! {
                      self._myList.append(User(name: items, value: true))
                    }
    
                    DispatchQueue.main.async {
                      self.tableView?.reloadData()
                    }
    
                }
        }
    

    并取出 .validate() ,如果你拿出来,你会看到更详细的错误描述 . 希望有所帮助 .

相关问题