2016-10-07 42 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欢迎伴侣:) –