在Swift中创建JSON数组 [英] Creating JSON Array in Swift
问题描述
我的后端期望使用以下JSON正文:
My backend is expecting the following JSON body:
[
{
"number":"561310"
},
{
"number":"132333"
},
{
"number":"561310"
}
]
当我这样输入时,它在Postman中效果很好:
It works very nicely in Postman when I enter it like so:
如何使用Swift创建类似的JSON? 现在,我有一个电话号码数组,类型为String.
How can I create a similar JSON using Swift? Right now I've an array of phone numbers with the type String.
let phonenumbers = [String]()
for phonenumber in phonenumbers {
print(phonenumber)
}
这将打印: 561310 132333 561310
This will print: 561310 132333 561310
制作完JSON之后,我想将其用作AlamoFire的参数.
After making this JSON I want to use it as a parameter for AlamoFire.
推荐答案
let phoneNumbersDictionary = phonenumbers.map({ ["number": $0] })
但是,Alamofire.request
期望POST主体为[String: AnyObject?]
形式,因此您不能直接传递上述数组.您需要使用
However, Alamofire.request
expects the POST body to be in form of [String: AnyObject?]
so you can't directly pass the above array in. You need to convert that to a JSON object using .dataWithJSONObject(options:)
and pass via NSURLRequest
:
let JSON = try? NSJSONSerialization.dataWithJSONObject(phoneNumbersDictionary, options: [])
let request = NSMutableURLRequest(URL: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = JSON
Alamofire.request(request).responseJSON { ...
顺便说一句,dataWithJSONObject
返回NSData
类型的结果,因此,如果要打印出来,应该将其转换为字符串:
By the way, dataWithJSONObject
returns the result of NSData
type, so you should convert it to string if you want to print that out:
if let JSON = JSON {
print(String(data: JSON, encoding: NSUTF8StringEncoding))
}
此外,如果您更喜欢使用内置的NSURLSession
库,请查看此
Additionally, if you prefer going with the built-in NSURLSession
library, please take a look at this SO question.
这篇关于在Swift中创建JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!