2016-10-07 48 views
0

我試圖使用序列斯威夫特3 JSON,並上來短.. 這是JSON(總結):SWIFT 3 JSON序列

{ 
    "values": [ 
    { 
     "a": { 
     "b": "1", 
     "c": { 
      "d": 0.0 
     } 
     }, 
     "wantThisOne": "2016-10-07T08:47:00Z" 
    }, 
    { 
     "a": { 
     "b": "1", 
     "c": { 
      "d": 0.0 
     } 
     }, 
     "notThisOne": "2016-10-07T09:05:00Z" 
    } 
    ] 
} 

我想要的日期從 'wantThisOne' ,但不知道如何得到它... 這是盡我所能,但沒有我嘗試在如果讓塊似乎爲我工作...任何人處理這樣的事情?我已經看過堆棧溢出等......但超級卡住了。

NSURLConnection.sendAsynchronousRequest(request1 as URLRequest, queue: queue, completionHandler:{ (response: URLResponse?, data: Data?, error: Error?) -> Void in 
     do { 
      if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { 
       print(jsonResult) 
      } 
     } catch let error as NSError { 
      print(error.localizedDescription) 
     } 
    }) 

回答

2

首先在斯威夫特使用通用型Dictionary[String:Any]而不是NSDictionary,你會得到字典後,從value鍵獲取數組,並通過遍歷數組,並從每個對象獲得wantThisOne

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { 
    if let valueArray = jsonResult["values"] as? [[String:Any]] { 
      for item in valueArray { 
       print("Date - \(item["wantThisOne"])") 
      } 
    } 
} 
+1

@Richie歡迎伴侶:) –