我有以下json作为响应:

[
{
    "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"
}
]

我试图将其解析为NSArray,如下所示:
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)
            }
        }

我总是得到错误:
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.}

我究竟做错了什么?

最佳答案

我认为您可以尝试使用此方法,并使用允许NSJSONReadingOptions.AllowFragments选项为您提供适当的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)'")
        }
    }

10-04 19:46