Alamofire请求JSON

时间:2015-06-11 15:02:50

标签: json swift alamofire

我需要向以下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
        }
    }
]

}

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

由于

1 个答案:

答案 0 :(得分:0)

由于您希望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",       "用户名" :" TestUsername"     },     " sistemaId" :" 2",     " contatos" :[       {         " idTipoContato" :{           " idContato" :1         },         " desContato" :" test@test.com"       }     ]   }