2017-05-27 61 views
-1

我試圖從API獲取數據並將其轉換爲swift。我設法連接到API,並獲取數據進入控制檯,但是當我嘗試解析數據時,我遇到了一個問題 - 下面是執行連接並解析數據的函數。使用Swift從API解析JSON數據的問題

我有線路的問題:

let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray 

運行的應用程序(功能parseData()被內viewDidLoad()調用)時,控制檯將產生以下它產生致命錯誤SIGABRT - Could not cast value of type '__NSDictionaryI' (0x103b7f288) to 'NSArray' (0x103b7ee28).

func parseData() { 

    let url = "https://api.***" 

    var request = URLRequest(url: URL(string: url)!) 

    let headers = [ 
     "user": "***", 
     "auth": "***" 
    ] 

    request.httpMethod = "GET" 
    request.allHTTPHeaderFields = headers 

    let configuration = URLSessionConfiguration.default 

    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main) 

    let task = session.dataTask(with: request) { (data, response, error) in 
     if (error != nil) { 
      print("Error") 
     } else { 
      do { 

       let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray 

       for eachFetchedOpportunity in fetchedData { 

        let eachOpportunity = eachFetchedOpportunity as! [String : Any] 
        let opportunity = eachOpportunity["subject"] as! String 
        let startDate = eachOpportunity["starts_at"] as! String 

        self.fetchedOpportunitys.append(Opportunity(opportunityName: opportunity, startDate: startDate)) 

       } 

       print(self.fetchedOpportunitys) 

      } catch { 
       print("Error") 
      } 
     } 
    } 

    task.resume() 

} 

這是從我通過郵遞員訪問的服務器返回的數據的開始(我沒有包括所有的數據,因爲有些數據是私人的和不必要的)我相信我的問題可能在於這裏存在字典和數組混合的事實,並且我不知道如何在這種情況下正確解析數據。

{ 
"opportunities": [ 
    { 
     "id": 3, 
     "store_id": 1, 
     "project_id": null, 
     "member_id": 5, 
     "billing_address_id": 5, 
     "venue_id": null, 
     "tax_class_id": 1, 
     "subject": "***", 
     "description": "", 
     "number": "00000000**", 
     "starts_at": "2017-05-27T08:00:00.000Z", 
     "ends_at": "2017-05-27T16:00:00.000Z", 
     "charge_starts_at": "2017-05-27T08:00:00.000Z", 
     "charge_ends_at": "2017-05-27T16:00:00.000Z", 
     "ordered_at": "2017-05-25T21:10:00.000Z", 
     "quote_invalid_at": null, 
     "state": 3, 
... 
... 
    } 
    ], 
    "meta": { 
    "total_row_count": 2, 
    "row_count": 2, 
    "page": 1, 
    "per_page": 12 
    } 
} 

回答

0

JSON響應DictionaryArray和你正在尋找的陣列是,你需要從字典中獲得opportunities

do { 
    let fetchedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any] 
    let opportunities = fetchedData["opportunities"] as? [[String:Any]] ?? [] 
    for opportunity in opportunities {  

     let subject = opportunity["subject"] as? String ?? "Default Subject" 
     let startDate = opportunity["starts_at"] as? String ?? "Default Date" 
     self.fetchedOpportunitys.append(Opportunity(opportunityName: subject, startDate: startDate)) 
    } 
} 
catch { 
    print("Error") 
} 
+0

完美的,你非常,這是一個夢想。我認爲這將是這樣的,但因爲我是新的迅速(字面上是最後幾天)不知道的語法 –

+0

@LewieClarke歡迎伴侶:) –