【问题标题】:Post request in swift with encodable [closed]使用可编码的 swift 发布请求 [关闭]
【发布时间】:2019-03-14 06:00:14
【问题描述】:

我想快速创建一个发布请求,但我对Encodable 协议感到困惑。以及如何创建它们。

以下是我要发布的数据:

{
answers: [{
            "time": 1,
            "score": 20,
            "status": true,
            "answer": 456
 }],
challenge_date": "2019-03-13"  
}

如何使用EncodableJSONSerialization 发布?

【问题讨论】:

  • Q1. 您的POST 请求是什么样的? Q2. 这必须是一个 json 字符串,你不能把它变成一个 [String:Any] 对象吗? Q3.你有这个Codable 模型吗?
  • 另外,您的 json 结构无效。根对象是一个字典,但该数组没有与任何键名相关联

标签: ios swift post nsjsonserialization encodable


【解决方案1】:

这个 JSON 是错误的。您的 JSON 必须有效。为了使上面的 JSON 有效,我们需要用一个键设置数组。

错误

{
 [{
            "time": 1,
            "score": 20,
            "status": true,
            "answer": 456
 }],
challenge_date": "2019-03-13"  
}

正确

{
    "array": [{
                "time": 1,
                "score": 20,
                "status": true,
                "answer": 456
     }],
    "challenge_date": "2019-03-13"  
}

上述 JSON 的 Swift 模型是这样的。

struct YourJSONModel: Codable {
    var challenge_date: String
    var array: Array<ResultModel>
}
struct ResultModel: Codable {
    var time: Int
    var score: Int
    var status: Bool
    var answer: Int
}

var result = ResultModel()
result.time = 10
result.score = 30
result.status = true
result.answer = 250


var jsonModel = YourJSONModel()
jsonModel.array = [result]
jsonModel.challenge_date = "2019-03-13"

将上述模型转换为 json 数据以发布。使用下面的代码。

let jsonData = try! JSONEncoder().encode(jsonModel)

var request = URLRequest(url: yourApiUrl)
request.httpBody = jsonData
request.httpMethod = "POST"

Alamofire.request(request).responseJSON { (response) in
            switch response.result {
            case .success:
                print(response)                    
            case .failure(let error):
                print(error.localizedDescription)
            }
}

【讨论】:

    【解决方案2】:

    使用Alamofire并将参数作为字典传递encoding: JSONEncoding.default,见以下代码。

        Alamofire.request(urlString!, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: headers)
            .responseJSON { (response) in
                switch response.result {
                case .success:
                    print(response)                    
                case .failure(let error):
                    print(error.localizedDescription)
                }
        }
    

    【讨论】:

    • 这里的Parameter 是什么?你能用我的数据展示它吗?
    • 参数只是传递给你的 [String:Any] 类型字典,你要传入 API 调用。
    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 2021-03-05
    • 2019-04-13
    • 2019-06-19
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多