无法在swift 2中将json数组解析为nsarray

时间:2015-09-02 09:50:30

标签: ios arrays json swift

我有以下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.}

我做错了什么?

3 个答案:

答案 0 :(得分:2)

我想你试试这个并使用allow 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)'")
        }
    }

答案 1 :(得分:1)

您获得的数据显然不是包含JSON的UTF-8字符串。我们可以看到这个,因为字符串似乎设置为

Current character set: utf8
NULL 

打印出错误信息时。

我首先从普通的Web浏览器发出URL请求,以确保响应符合您的预期。

答案 2 :(得分:-1)

对于swift 3和Xcode 8.1,您可以使用:

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