如何使用swift在字典中添加多个参数[String,Dictionary]?

时间:2015-07-01 07:50:56

标签: json swift nsdictionary nsjsonserialization

我正在使用Swift构建iOS应用程序。我正在使用XCODE版本6.3。 我想使用JSON将数据发布到服务器。为此我创建了一个字典来执行以下操作。

//This is my dictionary right now
 var parameters = ["authenticity_token":name,"platform":"mobileApp", "email": userEmail, "password": userPassword,"remember_me":"1"]

 request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)

我想以下面显示的格式传递数据。

{"authenticity_token":"token","platform":"mobileApp",
"user":{"email":"email_id", "password":"123456",
 "remember_me":"1"}}

现在格式

中的参数字典
[platform: mobileApp, authenticity_token: a1oj3olt5jn169LHn59ZbfbrBVUyov7sDVHlOl+2YzE=, email: su@gmail.com, remember_me: 1, password: samrat]

参数的顺序也发生了变化。 我想传递给我的字典。 或者是否有可能添加两个词典。

这是我将数据发布到服务器的代码。我还有另一个混淆是否正确。

 func postData()
  {
     let name = defaults.stringForKey("secretKey")

    var parameters = ["authenticity_token":name,"platform":"mobileApp", "email": userEmail, "password": userPassword,"remember_me":"1"]

    println("Dic\(parameters)")
    let url = NSURL(string: "http://behance.moblearn.net/users/sign_in")
    var session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)

     let jsonStr = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    println("Post Method reached")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

    println("Response: \(response)")
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("Body: \(strData)")
    var err: NSError?
    var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

      if(err != nil) {
        println(err!.localizedDescription)
        let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Error could not parse JSON: '\(jsonStr)'")
    }
    else {

        if let parseJSON = json {
            var success = parseJSON["success"] as? Int
            println("Succes: \(success)")
        }
        else {
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: \(jsonStr)")
        }
    }
})
task.resume()
}

我陷入了深深的麻烦。我是swift的初学者。帮助将受到赞赏。

1 个答案:

答案 0 :(得分:3)

这样做:

let innerDict = ["email": "email_id", "password": "123456", "remember_me": "1"]
let mainDict = ["authenticity_token": "token", "platform": "mobileApp", "user": innerDict]