Alamofire 请求 JSON

Alamofire request JSON

我需要向以下人提出请求JSON

{
"usuario": {
    "nmeUsuario": "name",
    "username": "TestUsername",
    "senha": "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5"
},
"sistemaId": "2",
"contatos": [
    {
        "desContato": "test@test.com",
        "idTipoContato": {
            "idTipoContato": 1
        }
    }
]

}

我尝试了以下代码

let senha = "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5"
let usuario = ["nmeUsuario":"name","username":"TestUsername","senha":senha]
let idContato = ["idContato":1]
let idTipoContato = ["idTipoContato":idContato]
let desContato = ["desContato":"test@test.com"]
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)
    }

但是 request.HTTPBody 中的 json 看起来像这样:

{
"usuario": {
    "nmeUsuario": "name",
    "senha": "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5",
    "username": "TestUsername"
},
"sistemaId": "2",
"contatos": [
    {
        "desContato": "test@test.com"
    },
    {
        "idTipoContato": {
            "idContato": 1
        }
    }
]

}

有什么办法可以解决这个问题吗?

谢谢

由于您希望 contatos 的数组包含单个字典,因此您需要像这样声明您的对象:

let senha = "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5"
let usuario = ["nmeUsuario":"name","username":"TestUsername","senha":senha]
let desContato = ["desContato":"test@test.com", "idTipoContato": ["idContato":1]]
let parameters = ["usuario":usuario,"sistemaId":"2", "contatos": [desContato]]

结果:

{ "usuario" : { "nmeUsuario" : "name", "senha" : "46070d4bf934fb0d4b06d9e2c46e346944e322444900a435d7d9a95e6d7435f5", "username" : "TestUsername" }, "sistemaId" : "2", "contatos" : [ { "idTipoContato" : { "idContato" : 1 }, "desContato" : "test@test.com" } ] }