Chen Li Yong Chen Li Yong - 1 year ago 58
JSON Question

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:


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.

Answer Source

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")
param.setValue(60, forKey:"id")

Pass the dict as the parameter for the request method.