Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Error when posting JSON

Tags:

json

post

ios

swift

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.

like image 527
dozo Avatar asked Aug 21 '16 00:08

dozo


1 Answers

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.

like image 102
Yann Bodson Avatar answered Nov 15 '22 04:11

Yann Bodson