2016-09-09 72 views
0

我正在嘗試學習Swift。我的一個項目是嘗試從內部Web服務(一組Python Python CGI腳本)中檢索JSON數據並將其轉換爲Swift對象。我可以在Python中輕鬆完成此任務,但在Swift中執行此操作時遇到了問題。這裏是我的遊樂場代碼:使用Swift將JSON轉換爲數據時遇到困難

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對象。

+0

JSON以'CRLF'(0x0D0A)開頭,這可能是問題所在 – vadian

回答

0

我想通了什麼是錯的。我正在鑄造錯誤的類型。這是新代碼:

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

JSON沒有返回一個字典數組,而是一個對象數組。

相關問題