Reputation: 115
I'm having problems with JSON Serialization in swift.
My code looks like:
var username = "xcode"
var password = "pass"
let json = ["username":username, "password":password]
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
var request = URLRequest(url: URL(string: "myServer")!)
request.httpMethod = "POST"
request.httpBody = jsonData
My problem is that when I make the petition to the server (which works fine), it returns me this line of code:
responseString = Optional("{\"username\":[\"This field is required.\"],\"password\":[\"This field is required.\"]}")
What am I doing wrong?
Upvotes: 1
Views: 3994
Reputation: 115
The code should be:
var username = "xcode"
var password = "pass"
let json = ["username":username, "password":password]
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
var request = URLRequest(url: URL(string: "http://10.192.118.193:8000/users/")!)
request.httpMethod = "POST"
request.httpBody = jsonData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
Upvotes: 2