加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 通过Alamofire发送json数组

发布时间:2020-12-14 06:04:46 所属栏目:百科 来源:网络整理
导读:我想知道是否可以在POST请求中直接发送数组(不包含在字典中)。显然参数参数应该得到一个映射:[String:AnyObject]? 但我想能够发送以下示例json: [ "06786984572365","06644857247565","06649998782227"] 你可以用NSJSONSerialization编码JSON,然后自己
我想知道是否可以在POST请求中直接发送数组(不包含在字典中)。显然参数参数应该得到一个映射:[String:AnyObject]?
但我想能够发送以下示例json:
[
    "06786984572365","06644857247565","06649998782227"
]
你可以用NSJSONSerialization编码JSON,然后自己生成NSURLRequest。例如,在Swift 2:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json",forHTTPHeaderField: "Content-Type")

let values = ["06786984572365","06649998782227"]

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values,options: [])

Alamofire.request(request)
    .responseJSON { response in
        // do whatever you want here
        switch response.result {
        case .Failure(let error):
            print(error)

            // if web service reports error,sometimes the body of the response
            // includes description of the nature of the problem,e.g.

            if let data = response.data,let responseString = String(data: data,encoding: NSUTF8StringEncoding) {
                print(responseString)
            }
        case .Success(let responSEObject):
            print(responSEObject)
        }
}

或者,在Swift 3:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json","06649998782227"]

request.httpBody = try! JSONSerialization.data(withJSONObject: values)

Alamofire.request(request)
    .responseJSON { response in
        // do whatever you want here
        switch response.result {
        case .failure(let error):
            print(error)

            if let data = response.data,encoding: .utf8) {
                print(responseString)
            }
        case .success(let responSEObject):
            print(responSEObject)
        }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读