使用Swift将JSON转换为数据时遇到问题

时间:2016-09-09 00:53:17

标签: json swift

我正在努力学习斯威夫特。我的一个项目是尝试从内部Web服务(一组Python CGI脚本)中检索JSON数据并将其转换为Swift对象。我可以在Python中轻松完成这项工作,但我在Swift中无法做到这一点。这是我的游乐场代码:

import UIKit

import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let endpoint: String = "http://pathToCgiScript/cgiScript.py"
let url = NSURL(string: endpoint)
let urlrequest = NSMutableURLRequest(URL: url!)
let headers: NSDictionary = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"]
urlrequest.allHTTPHeaderFields = headers as? [String : String]
urlrequest.HTTPMethod = "POST"

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlrequest) {
    (data, response, error) in
    guard data != nil else {
        print("Error: did not receive data")
        return
    }
    guard error == nil else {
        print("Error calling script!")
        print(error)
        return
    }
    do {
        guard let received = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as?
        [String: AnyObject] else {
            print("Could not get JSON from stream")
            return
        }
        print(received)

    } catch {
        print("error parsing response from POST")
    }
}
task.resume()

我知道发布' POST'检索数据可能看起来很奇怪,但这就是系统的设置方式。我继续得到:

Could not get data from JSON

我检查了回复,状态为200.然后我检查了数据的描述:

print(data?.description)

我得到了意想不到的结果。这是一个片段:

Optional("<0d0a5b7b 22535441 54555322 3a202244 6f6e6522 2c202242 55535922...

我使用了Mirror,显然类型是NSData。不知道该怎么做。我试图用base64EncodedDataWithOptions对数据进行编码。我尝试过不同的NSJSONReadingOptions也无济于事。有什么想法吗?

更新

我使用Wireshark仔细检查Playground中的代码。不仅呼叫正确,而且发回的数据也是正确的。事实上,Wireshark将数据视为JSON。问题是尝试将JSON数据转换为Swift对象。

1 个答案:

答案 0 :(得分:0)

我弄清楚出了什么问题。我投的是错误的类型。这是新代码:

guard let received = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [AnyObject] 

JSON没有返回一个字典数组,而是返回一个对象数组。