3

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.

Rutger Huijsmans
  • 2,330
  • 2
  • 30
  • 67
  • Possible duplicate of http://stackoverflow.com/questions/39439211/how-to-convert-array-of-dictionary-to-json – Eric Aya Oct 03 '16 at 08:16

3 Answers3

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

Community
  • 1
  • 1
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • 1
    Awesome man! Thanks a bunch for typing out both options and referring to the other SO question. – Rutger Huijsmans Oct 03 '16 at 09:34
  • Ah wait, 1 problem though... I cannot add phoneNumbersDictionary as parameters: of the request. It says it's getting [[String:String]] but expecting [String:AnyObject]? – Rutger Huijsmans Oct 03 '16 at 09:42
  • @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. – Ozgur Vatansever Oct 03 '16 at 10:04
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 = (["key1": value.someVariable, "key2": value.someOtherVariable ])
            jsonArray.append(json as! [String : String])
        }
        print(jsonArray)
        return jsonArray
    }

and use this map() as param in Alamofire

Sultan Ali
  • 2,497
  • 28
  • 25
1

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.

onCompletion
  • 6,500
  • 4
  • 28
  • 37