问题
My backend is expecting the following JSON body:
[
{
"number":"561310"
},
{
"number":"132333"
},
{
"number":"561310"
}
]
It works very nicely in Postman when I enter it like so:
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)
}
This will print: 561310 132333 561310
After making this JSON I want to use it as a parameter for AlamoFire.
回答1:
let phoneNumbersDictionary = phonenumbers.map({ ["number": $0] })
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 { ...
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))
}
Additionally, if you prefer going with the built-in NSURLSession
library, please take a look at this SO question.
回答2:
You may use array of dictionary feature in swift.
For example you can create same like as follows:
var phonenumbers = [[String: String]]()
let dataToAppend: [String: String] = ["number": "561310"]
phonenumbers.append(dataToAppend)
phonenumbers.append(dataToAppend)
phonenumbers.append(dataToAppend)
for phonenumber in phonenumbers {
print(phonenumber)
}
Remember this is just a type of approach which you can follow. Though there are lots of different procedure to make this kind of things.
In your case you can update the key value pair by running a loop through the phonenumbers
array and append the new data to the main array which you gonna send as header to your backend.
Thanks.
Hope this helped.
回答3:
in my scenario i needed to sent the data in this formate
[ {"id": "123" , "value":, "this is value"},
{"id": "123" , "value":, "this is value"},
{"id": "123" , "value":, "this is value"} ]
i solved it like this
func map() -> [[String: String]]{
var jsonArray: [[String: String]] = [[String: String]]()
//here data is arra of objets or values where your data exist, if your data is not in an array you can user object or what ever format you have like this jsonArray.append(["key": "value", "key":"value"])
for value in data {
let json = (["key": "value", "key":"value"])
jsonArray.append(json as! [String : String])
}
print(jsonArray)
return jsonArray
}
and use this map() as param in Alamofire
来源:https://stackoverflow.com/questions/39826824/creating-json-array-in-swift