json数据即将出现null我错过了什么?

时间:2015-05-27 10:03:42

标签: ios json xcode swift

class RemoteAPI
    {
        func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void {
            let url: NSURL = NSURL(string:"http://192.168.0.31:8097/api/asset/GetFile?username=supreetha.shivananda@vicoast.com&RoleName=null&GroupName=null&EntityIdParam=1&StartIndex=1&EndIndex=300&PageIndex=0&PageSize=500&ItemsPerPage=1&Sort=0&EntityIdWithIndex=1&GName=null&GDesc=null&GId=null")!

            let ses = NSURLSession.sharedSession()
            let task = ses.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
                println("Task completed")
                if (error != nil)
                {
                    return completionHandler(nil, error)
                }

                var err: NSError?
                if(data != nil)
                {
                    // let json = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary
                    var json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &err) as NSDictionary
                    if let unwrappedError = err
                    {
                        println("JSON Error \(err!.localizedDescription)")
                    }
                }
            })
            task.resume()
        }
    }

通过上面的函数我调用一个json数据并解析它,但是当我运行并调试数据时会出现空值

 let task = ses.dataTaskWithURL(url, completionHandler: {data, response, error ->

当我检查数据和响应时,我得到的值就像 打印回复说明:

(NSURLResponse!) response = Some {
  Some = 0x2030663666316632 {
    ObjectiveC.NSObject = {}
  }
}

打印数据描述:

(NSData!) data = Some {
  Some = 0x726f636572202c7d {
    ObjectiveC.NSObject = {}
  }
}

之后我检查数据的非空条件 喜欢

if(data != nil)
{
var json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &err) as NSDictionary
}

在执行json序列化时会抛出EX_BAD_EXCEPTION

为什么我从json url获取null?是我接近的方式是错的? 如果我运行网址我在浏览器上获得json值我没有得到什么错误可以任何人请建议我被打入这个

1 个答案:

答案 0 :(得分:0)

我怀疑你的反应格式是不是校正者。试试这个。

if(data != nil) {
    // let json = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary
    var json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &err) as? AnyObject
    if let unwrappedError = err {
           println("JSON Error \(err!.localizedDescription)")
    }
    if json is [AnyObject] {
        println("The response is array")
     }
     if json is [String:AnyObject] {
        println("The response is dictionary")
    }
  }