1

I have the following json as a response :

[
{
    "id_post": "1",
    "id_type": "1",
    "title": "I hffjj",
    "body": "nothing at all",
    "visitors": "0",
    "extrabutton": "none",
    "deviceid": "468af7f24ade50c9"
},
{
    "id_post": "2",
    "id_type": "1",
    "title": "suxk my ",
    "body": "sssusushshd",
    "visitors": "0",
    "extrabutton": "none",
    "deviceid": "468af7f24ade50c9"
}
] 

I am trying to parse it as an NSArray as the following :

let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray {
                    print("Success: \(jsonResult)")
                }
            } catch let parseError {
                print(parseError)
            }
        }

I always get the 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.}

What am I doing wrong?

1
  • Minor point, but if you change your guard to guard let data = data else { .... } you can do away with the exclamation marks in the following code. Commented Sep 2, 2015 at 9:55

3 Answers 3

2

I think you try this one and use allow NSJSONReadingOptions.AllowFragments options which give you a proper json

let task = session.dataTaskWithRequest(request) { data, response, error in guard data != nil else {
           print("no data found: \(error)")
            return
           }

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments | NSJSONReadingOptions.MutableContainers, error: nil) as? NSArray {
                print("Success: \(jsonResult)")
            }
        } catch let parseError {
            print(parseError)
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Another error: Binary operator cannot be applied to two NSJSONReadingOptions operands.
Try options:[.AllowFragments, .MutableContainers]. The syntax changed in Swift 2.
The options worked, the error is "Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}" now.
1

The data you get back is clearly not a UTF-8 string containing JSON. We can see this because the string appears to be set to

Current character set: utf8
NULL 

when the error message is printed out.

I'd start by issuing the URL request from an ordinary web browser to make sure that the response is what you expect.

2 Comments

The response is what I expect. My problem isn't the utf8 encoding but the "JSON text did not start with array or object and option to allow fragments not set." utf8 is in the error handling branch
@xanyi Yesterday your question contained a second error message which printed out the content of the data which was clearly not a JSON string. Why do you think this is not relevant? It would cause exactly the problem you are seeing,
-1

For swift 3 and Xcode 8.1 you can use this:

 let jsonResult = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments, .mutableContainers])

1 Comment

The JSON in the question doesn't need any of those options and .mutableContainers is meaningless in Swift anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.