如何在swift中将json传递给服务器

时间:2016-03-23 07:30:18

标签: ios json swift

这是我想传递给json到服务器的json格式:

 {"student":[{"student_persnal":{"name":"","age":""}},{"contact":[{"address":{"street":"","area":"","city":"","zipcode":""},{"street":"","area":"","city":"","zipcode":""}}]}]}   

我使用以下代码:

var students_final: String = ""

do {
        let students1 = try NSJSONSerialization.dataWithJSONObject(student, options: NSJSONWritingOptions())

        if let students = String(data: students1, encoding: NSUTF8StringEncoding) {

            students_final = students

        }

    } catch let error as NSError {
        print(error)
    }

1 个答案:

答案 0 :(得分:1)

我写了一个示例代码,用于向服务器发送数据。你可以为你定制它。见下面的代码。

var json_example = "[{ \"id\": 1, \"name\": \"test\" },{ \"id\": 2, \"name\": \"test\" }]"
let data = json_example.dataUsingEncoding(NSUTF8StringEncoding)

let request = NSMutableURLRequest(URL: NSURL(string: "your_string_url")!)
request.HTTPBody = data
request.HTTPMethod = "Your_http_method" // GET/POST/DELETE

NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
    // Receive response from your server
}

希望有所帮助。