jsonswiftswifty-json

Creating JSON Array in Swift


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:

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 {
    print(phonenumber)
}

This will print: 561310 132333 561310

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


Solution

  • 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.