Rutger Huijsmans Rutger Huijsmans - 11 months ago 64
JSON Question

Creating JSON Array in Swift

My backend is expecting the following JSON body:


It works very nicely in Postman when I enter it like so:

enter image description here

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 {

This will print:

After making this JSON I want to use it as a parameter for AlamoFire.

Answer Source
let phoneNumbersDictionary ={ ["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.