【问题标题】:JSON.dictionaryObject is null in Alamofire swift 3JSON.dictionaryObject 在 Alamofire swift 3 中为空
【发布时间】:2017-04-17 09:25:39
【问题描述】:

我有一个以下格式的 JSON:

postJson ={"firstname":"Vishal","lastname":"raskar","username":"vishal123","password":"123456","confirmpassword":"123456","email":"raskarvishal7@gmail.com","timezone":"1","accountid":"12345","phoneno":"8655012753"}

(postJson 的数据类型是 JSON 即 swiftyJSON)

现在我想通过 Alamofire 访问服务器,所以我需要在 parameters : ___ 中以字典格式发布 JSON 数据,例如:

Alamofire.request(URL, method: .post, parameters: postJson.dictionaryObject, encoding: JSONEncoding.default,headers: "Content-Type": "application/json").responseJSON { response in switch response.result {

case .success(let data):

case .failure(let error):

}

所以基本上我尝试通过postJson.dictionaryObject 将我的JSON 转换为字典。但总是从postJson.dictionaryObject 得到空值(即使postJson 中存在数据)。

我尝试了所有组合,例如postJson.dictionaryValuepostJson.dictionary,但没有成功。

然后我尝试将postJson 转换为Data,然后是字典:

if let data = postJson.data(using: .utf8) {

 do {

return try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
            } 
catch {

 print(error.localizedDescription)

 }

 }

然后通过 Alamofire 发帖,现在得到响应。我究竟做错了什么?我想使用我的第一个选项。

【问题讨论】:

  • 可以直接使用["firstname":"Vishal","lastname":"raskar","username":"vishal123","password":"123456","confirmpassword":"123456","email":"raskarvishal7@gmail.com","timezone":"1","accountid":"12345","phoneno":"8655012753"]作为请求的参数,不需要转换成swiftyjson对象。

标签: json swift alamofire swifty-json


【解决方案1】:

假设您使用的是 Swift 3 / Alamofire 4.0

这是根据 Alamofire 文档定义“参数”参数的方式:

let parameters: Parameters = ["foo": "bar"]

Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default)
    .downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
        print("Progress: \(progress.fractionCompleted)")
    }
    .validate { request, response, data in
        // Custom evaluation closure now includes data (allows you to parse data to dig out error messages if necessary)
        return .success
    }
    .responseJSON { response in
        debugPrint(response)
    }

要了解更多信息,click here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多