I keep getting an error when trying to send JSON data to a site. But when I check the site, I see that all the data in json was sent and is correct.
The error I get is:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
The code I have is:
let json = [
"name": "john",
"last name": "smith"
]
do{
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
let url = NSURL(string: website)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error: \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result: \(result)")
} catch {
print("Error: \(error)")
}
}
task.resume()
} catch {
print(error)
}
When I allow for fragments:
try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
I get another error:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
I changed:
try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
to
try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)
and I no longer get an error.
The error happens when you print your result after the data is successfully sent to server.
NSJSONSerialization.JSONObjectWithData
requires the JSON to start with an object ({}
) or an array ([]
).
Try adding the .AllowFragments
option like this:
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String:AnyObject]
If it doesn't work, the data coming back from the server is invalid JSON. You should try printing the response
's statusCode
and see if there is a problem.
If you control the server, you should look at what is sent back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With