JSON error while sending JSON

I keep getting an error when I try to send JSON data to the site. But when I check the site, I see that all the data in json has been sent and is correct.

The error I am getting 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 admit 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 the error message.

+5
source share
1 answer

The error occurs when you print the result after the data has been successfully sent to the server.

NSJSONSerialization.JSONObjectWithData requires JSON to start with an object ( {} ) or an array ( [] ).

Try adding the .AllowFragments parameter as follows:

 let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String:AnyObject] 

If it does not work, the data returned from the server is invalid JSON. You should try to print response statusCode and see if there is a problem.

If you are managing a server, you should see what is sent back.

+1
source

All Articles