在Swift中正确解析JSON 3

前端之家收集整理的这篇文章主要介绍了在Swift中正确解析JSON 3前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图获取一个JSON响应,并将结果存储在一个变量。我有这个代码的版本工作在以前的版本的Swift,直到GM版本的Xcode 8发布。我看了几个类似的帖子在StackOverflow: Swift 2 Parsing JSON – Cannot subscript a value of type ‘AnyObject’JSON Parsing in Swift 3

然而,似乎在那里传达的想法不适用于这种情况。

如何正确解析Swift 3中的JSON响应?
在Swift 3中读取JSON的方式有什么变化?

下面是有问题的代码(它可以在操场上运行):

  1. import Cocoa
  2.  
  3. let url = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
  4.  
  5. if let url = NSURL(string: url) {
  6. if let data = try? Data(contentsOf: url as URL) {
  7. do {
  8. let parsedData = try JSONSerialization.jsonObject(with: data as Data,options: .allowFragments)
  9.  
  10. //Store response in NSDictionary for easy access
  11. let dict = parsedData as? NSDictionary
  12.  
  13. let currentConditions = "\(dict!["currently"]!)"
  14.  
  15. //This produces an error,Type 'Any' has no subscript members
  16. let currentTemperatureF = ("\(dict!["currently"]!["temperature"]!!)" as NSString).doubleValue
  17.  
  18. //Display all current conditions from API
  19. print(currentConditions)
  20.  
  21. //Output the current temperature in Fahrenheit
  22. print(currentTemperatureF)
  23.  
  24. }
  25. //else throw an error detailing what went wrong
  26. catch let error as NSError {
  27. print("Details of JSON parsing error:\n \(error)")
  28. }
  29. }
  30. }

编辑:以下是打印后的API调用的结果示例(currentConditions)

  1. ["icon": partly-cloudy-night,"precipProbability": 0,"pressure": 1015.39,"humidity": 0.75,"precipIntensity": 0,"windSpeed": 6.04,"summary": Partly Cloudy,"ozone": 321.13,"temperature": 49.45,"dewPoint": 41.75,"apparentTemperature": 47,"windBearing": 332,"cloudCover": 0.28,"time": 1480846460]
首先,不要从远程URL同步加载数据,请使用像URLSession这样的异步方法

‘Any’ has no subscript members

发生因为编译器不知道中间对象是什么类型的(例如当前在[“当前”]![“温度”]),并且由于您使用的是NSDictionary类的Foundation集合类型,编译器根本不知道类型。

此外,在Swift 3中,需要通知编译器有关所有下标对象的类型。

您必须将JSON序列化的结果转换为实际类型。

代码使用URLSession和独有的Swift本机类型

  1. let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
  2.  
  3. let url = URL(string: urlString)
  4. URLSession.shared.dataTask(with:url!) { (data,response,error) in
  5. if error != nil {
  6. print(error)
  7. } else {
  8. do {
  9.  
  10. let parsedData = try JSONSerialization.jsonObject(with: data!,options: []) as! [String:Any]
  11. let currentConditions = parsedData["currently"] as! [String:Any]
  12.  
  13. print(currentConditions)
  14.  
  15. let currentTemperatureF = currentConditions["temperature"] as! Double
  16. print(currentTemperatureF)
  17. } catch let error as NSError {
  18. print(error)
  19. }
  20. }
  21.  
  22. }.resume()

要打印所有可以写入的currentConditions的键/值对

  1. let currentConditions = parsedData["currently"] as! [String:Any]
  2.  
  3. for (key,value) in currentConditions {
  4. print("\(key) - \(value) ")
  5. }

编辑:

苹果在Swift博客中发表了一篇综合文章Working with JSON in Swift

猜你在找的Swift相关文章