Creating JSON Array in Swift
Solution 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.
Solution 2
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 = (["key1": value.someVariable, "key2": value.someOtherVariable ])
jsonArray.append(json as! [String : String])
}
print(jsonArray)
return jsonArray
}
and use this map() as param in Alamofire
Solution 3
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.
Rutger Huijsmans
Updated on June 04, 2022Comments
-
Rutger Huijsmans almost 2 years
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.
-
Rutger Huijsmans over 7 yearsAwesome man! Thanks a bunch for typing out both options and referring to the other SO question.
-
Rutger Huijsmans over 7 yearsAh wait, 1 problem though... I cannot add phoneNumbersDictionary as parameters: of the request. It says it's getting [[String:String]] but expecting [String:AnyObject]?
-
Ozgur Vatansever over 7 years@RutgerHuijsmans Yeah, I totally forgot that you can't pass an array to Alamofire.request using that function. You should create a NSURLRequest first. Updated my answer.