swift 3将json参数发布到api

时间:2016-09-25 12:38:48

标签: json swift3

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

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

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

{
    "customer": {
        "first_name": "Steve",
        "last_name": "Lastnameson",
        "email": "steve.lastnameson@example.com",
        "verified_email": true,
        "addresses": [
            {
                "address1": "123 Oak St",
                "city": "Ottawa",
                "province": "ON",
                "phone": "555-1212",
                "zip": "123 ABC",
                "last_name": "Lastnameson",
                "first_name": "Mother",
                "country": "CA"
            }
        ]
    }
}

这是我的发布代码:

let customer = [
    "customer": [
        "first_name": "Steve",
        "last_name": "Lastnameson",
        "email": "steve.lastnameson@example.com",
        "verified_email": "true",
        "addresses": [
            [
                "address1": "123 Oak St",
                "city": "Ottawa",
                "province": "ON",
                "phone": "555-1212",
                "zip": "123 ABC",
                "last_name": "Lastnameson",
                "first_name": "Mother",
                "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()

1 个答案:

答案 0 :(得分:5)

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

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