发布请求swift with encodable [关闭]

问题描述 投票:-6回答:2

我想在swift中创建一个post请求,但我在Encodable协议中感到困惑。以及如何创建它们。

以下是我要发布的数据:

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

我怎么能用EncodableJSONSerialization发布它?

ios swift post nsjsonserialization encodable
2个回答
0
投票

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

Wrong

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

Correct

{
    "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)
            }
}

0
投票

使用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)
            }
    }
© www.soinside.com 2019 - 2024. All rights reserved.