Swift:NSJSONSerialization.JSONObjectWithData返回nil,但json似乎没问题

时间:2015-05-13 09:24:30

标签: ios swift

我使用此代码获取JSON,但NSJSONSerialization.JSONObjectWithData返回nil,但JSON看起来没问题:

var url = "http://andreid.imcserver.ro/test/service.php"
var nsURL = NSURL(string: url)
        let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!){
            (data, response, error) in
            var error: NSError?
            var data2 = NSString(data: data, encoding: NSUTF8StringEncoding)
            println(data)
            println(data2)

            var response: NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary

            if let err = error {
                println("error parsing json")
                return
            }

2 个答案:

答案 0 :(得分:1)

我用SwiftyJSON尝试了这个。并且工作正常。

这是代码:

var url = "http://andreid.imcserver.ro/test/service.php"
var nsURL = NSURL(string: url)
let data = NSData(contentsOfURL: nsURL!)
let json = JSON(data: data!)
println(json)

答案 1 :(得分:1)

我尝试了您的代码,请参阅下面的编辑代码。

var url = "http://andreid.imcserver.ro/test/service.php"
        var nsURL = NSURL(string: url)
        var request = NSURLRequest(URL: nsURL!)
        var data: NSData
        var response: NSURLResponse?
        var error: NSErrorPointer?

        var jsonTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
            (data, response, error) -> Void in
            println("\(data)")
            println("\(response)")
            println("\(error)")

            if error == nil
            {
                var jsonError: NSError?
                var jsonResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &jsonError) as! NSDictionary

                println("\(jsonResponse)")

            }
            else
            {
                println("JSON PARse error")
            }
        })
        jsonTask.resume()

它适用于我。