xanyi
xanyi

Reputation: 127

Cannot parse json array as nsarray in swift 2

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?

Upvotes: 1

Views: 4190

Answers (3)

xhinoda
xhinoda

Reputation: 1068

For swift 3 and Xcode 8.1 you can use this:

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

Upvotes: -1

VSP
VSP

Reputation: 166

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)'")
        }
    }

Upvotes: 2

JeremyP
JeremyP

Reputation: 86651

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.

Upvotes: 1

Related Questions