Chen Li Yong
Chen Li Yong

Reputation: 6087

How to send dictionary with array using JSON?

My fellow co-worker backend programmer said that he has configure an API that expect to receive something like this from my mobile app:

[{"id":50},{"id":60}]

I'm using Alamofire which receive param dictionary to be sent. But I believe this is also the same mechanism using NSURLSession or any other third party plugins.

The question is: how should I construct the dictionary to send an array of ids, like how a HTTP form can have several text field with the same id, and then it will be received on the server end as an array of id? What I've tried so far and all fails:

param.setValue(50, forKey:"id");
param.setValue(60, forKey:"id");
// this only send the last single value

param.setValue([50, 60], forKey:"id");
// this results in error (415 unsupported media type)

param.setValue(50, forKey:"id[0]");
param.setValue(60, forKey:"id[1]");
// this also results in error (415 unsupported media type)

How can I send this correctly just like how web form send? Thanks.

Upvotes: 2

Views: 774

Answers (2)

Hưng Nguyễn
Hưng Nguyễn

Reputation: 31

I think keyword for your question is "Alamofire send json"

If your server accepts json data, you can do like this:

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let values = [["id":50],["id":60]]

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])

Alamofire.request(request)
    .responseJSON { response in

        // do whatever you want here

}

Good luck!

Upvotes: 3

ebby94
ebby94

Reputation: 3152

The problem with the first method is you're overwriting the value for the key id, that's the reason why it only sends the last value. Try sending the params as an array.

let dict = NSMutableArray()
param.setValue(50, forKey:"id")
dict.addObject(param)
param.setValue(60, forKey:"id")
dict.addObject(param)

Pass the dict as the parameter for the request method.

Upvotes: 2

Related Questions