2016-09-25 87 views
5

我需要将以下json传递给此函数,以便Shopify Api可以理解提交。swift 3将json参数发送到api

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

Shopify API期待下面的JSON通过POST

传递
{ 
    "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", 
       "last_name": "Lastnameson", 
       "first_name": "Mother", 
       "country": "CA" 
      } 
     ] 
    } 
} 

这里是我的邮政代码:

let customer = [ 
    "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", 
       "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() 
+0

从服务器获得的确切响应是什么? –

+1

创建一个新的客户账号 – Hamid

+0

问题是服务器没有以预期的格式获取数据 – Hamid

回答

5

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

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