微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift 3将json参数发布到api

我需要将以下json传递给此函数,以便Shopify Api可以理解提交.

每次执行此代码时,都会收到一条错误消息,指出缺少必需参数.显然,我无法创建正确的变量格式并将其传递给服务器.

Shopify API期望通过POST传递以下json

{
    "customer": {
        "first_name": "Steve","last_name": "Lastnameson","email": "[email protected]","verified_email": true,"addresses": [
            {
                "address1": "123 Oak St","city": "ottawa","province": "ON","phone": "555-1212","zip": "123 ABC","first_name": "Mother","country": "CA"
            }
        ]
    }
}

这是我的发布代码

let customer = [
    "customer": [
        "first_name": "Steve","verified_email": "true","addresses": [
            [
                "address1": "123 Oak St","country": "CA",],] as [String: Any]

var request = URLRequest(url: URL(string: shopUrl + "/admin/customers.json")!)
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: customer,options: [])

URLSession.shared.dataTask(with:request,completionHandler: {(data,response,error) in
    if error != nil {
        print(error)
    } else {
        do {
            guard let json = try? JSONSerialization.jsonObject(with: data!,options: .allowFragments) as? [String: Any] else { return }

            guard let errors = json?["errors"] as? [[String: Any]] else { return }
                if errors.count > 0 {
                    // show error
                    return
                } else {
                    // show confirmation
                }
            }
        }
    }).resume()

解决方法

请求需要声明内容类型.加:

request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐