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!

Evan Laksana
  • 410
  • 3
  • 7
  • 17
  • Have you checked this: http://stackoverflow.com/questions/40604502/post-request-with-data-in-body-with-alamofire-4, In your case the data looks like an array of dictionary so you can try `parameter: [ [ String: String] ] ` – NeverHopeless Apr 27 '17 at 07:57
  • its key:value but in my case only value without key :( – Evan Laksana Apr 27 '17 at 08: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 Apr 27 '17 at 08:10

1 Answers1

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)
Community
  • 1
  • 1
redent84
  • 18,901
  • 4
  • 62
  • 85