繁体   English   中英

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

[英]Cannot parse json array as nsarray in swift 2

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

我究竟做错了什么?

我认为您可以尝试使用此方法,并使用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)'")
        }
    }

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

Current character set: utf8
NULL 

当错误信息被打印出来时。

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

对于Swift 3和Xcode 8.1,可以使用以下命令:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM