Alamofire request JSON

367 views Asked by At

I need to make a request to the following JSON

{
"usuario": {
    "nmeUsuario": "name",
    "username": "TestUsername",
    "senha": "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5"
},
"sistemaId": "2",
"contatos": [
    {
        "desContato": "[email protected]",
        "idTipoContato": {
            "idTipoContato": 1
        }
    }
]

}

I tried the following code

let senha = "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5"
let usuario = ["nmeUsuario":"name","username":"TestUsername","senha":senha]
let idContato = ["idContato":1]
let idTipoContato = ["idTipoContato":idContato]
let desContato = ["desContato":"[email protected]"]
let contato = [desContato, idTipoContato]
let parameters = ["usuario":usuario,"sistemaId":"2", "contatos":contato]
Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON).response { (request, response, data, error) in
        var datastring = NSString(data: request.HTTPBody!, encoding:NSUTF8StringEncoding)
        println(datastring)
    }

however the json in request.HTTPBody looks like this:

{
"usuario": {
    "nmeUsuario": "name",
    "senha": "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5",
    "username": "TestUsername"
},
"sistemaId": "2",
"contatos": [
    {
        "desContato": "[email protected]"
    },
    {
        "idTipoContato": {
            "idContato": 1
        }
    }
]

}

Is there any way to solve this problem?

Thanks

1

There are 1 answers

0
Eric Aya On BEST ANSWER

Since you want contatos's array to contain a single dictionary, you need to declare your objects like this:

let senha = "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5"
let usuario = ["nmeUsuario":"name","username":"TestUsername","senha":senha]
let desContato = ["desContato":"[email protected]", "idTipoContato": ["idContato":1]]
let parameters = ["usuario":usuario,"sistemaId":"2", "contatos": [desContato]]

Result:

{ "usuario" : { "nmeUsuario" : "name", "senha" : "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5", "username" : "TestUsername" }, "sistemaId" : "2", "contatos" : [ { "idTipoContato" : { "idContato" : 1 }, "desContato" : "[email protected]" } ] }