RMP
RMP

Reputation: 9

How to pass json to the server in swift

This is my json format that I want to pass to the json to server:

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

I am using the following code:

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)
    }

Upvotes: 0

Views: 57

Answers (1)

Long Pham
Long Pham

Reputation: 7582

I write a sample code for send a data to server. You can custom it for you. See below code.

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
}

Hope that helps.

Upvotes: 1

Related Questions