1

So I want to sent parameter which like this:

I have a model like this:

class test{
  var id: String?
  var name: String?

}

Json i want :

[
{
 "id":"1",
 "name":"asda"

},
{

 "id":"2",
 "name":"asda"

}


]

and how to send that class as a parameter in alamofire ???

let parameter: [AnyObject] = listTest but it doesnt work :(

Any advice will be appreciated!

3
  • Have you checked this: stackoverflow.com/questions/40604502/…, In your case the data looks like an array of dictionary so you can try parameter: [ [ String: String] ] Commented Apr 27, 2017 at 7:57
  • its key:value but in my case only value without key :( Commented Apr 27, 2017 at 8:02
  • 3
    You can't send you object as such into Alamofire because it's not JSON valid. You may create a method for your class: toDict(), that will return a Dictionary [String:String], with ["id":id, "name":name], and then you create the array of theses.
    – Larme
    Commented Apr 27, 2017 at 8:10

1 Answer 1

1

To send a single JSON object to your server using Alamofire, you just have to convert your object to a serializable dictionary. For example:

extension Test {
    func toDict() -> [String: String] {
        return ["id": id ?? "", "name": name ?? ""]
    }
}

And send it specifying the correct JSON encoding:

let parameters = test.toDict()
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)

Sending an array of dictionaries instead of a dictionary is a little bit trickier. Code extracted from this answer:

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

let values = tests.map { $0.toDict() }

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

Alamofire.request(request)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.