swift 3 json序列化

时间:2016-10-07 08:58:31

标签: ios json swift serialization swift3

我试图使用Swift 3序列化JSON,并且很快就会出现问题。 这是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',但不确定如何获得它... 这是我得到的但是我试试if if block似乎对我有用......任何人都处理过这样的事情?我已经看过堆栈溢出等......但超级卡住了。

    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)
        }
    })

1 个答案:

答案 0 :(得分:2)

首先在Swift中使用泛型类型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"])")
          }
     }
}