在Swift中正确解析JSON 3

在Swift中正确解析JSON 3,第1张

概述我试图获取一个JSON响应,并将结果存储在一个变量。我有这个代码的版本工作在以前的版本的Swift,直到GM版本的Xcode 8发布。我看了几个类似的帖子在StackOverflow: Swift 2 Parsing JSON – Cannot subscript a value of type ‘AnyObject’和 JSON Parsing in Swift 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的方式有什么变化?

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

import Cocoalet url = "https://API.forecast.io/forecast/APIKey/37.5673776,122.048951"if let url = NSURL(string: url) {    if let data = try? Data(contentsOf: url as URL) {        do {            let parsedData = try JsONSerialization.JsonObject(with: data as Data,options: .allowFragments)        //Store response in NSDictionary for easy access        let dict = parsedData as? NSDictionary        let currentConditions = "\(dict!["currently"]!)"        //This produces an error,Type 'Any' has no subscript members        let currentTemperatureF = ("\(dict!["currently"]!["temperature"]!!)" as Nsstring).doubleValue            //display all current conditions from API            print(currentConditions)            //Output the current temperature in Fahrenheit            print(currentTemperatureF)        }        //else throw an error detailing what went wrong        catch let error as NSError {            print("Details of JsON parsing error:\n \(error)")        }    }}

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

["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本机类型

let urlString = "https://API.forecast.io/forecast/APIKey/37.5673776,122.048951"let url = URL(string: urlString)URLSession.shared.dataTask(with:url!) { (data,response,error) in  if error != nil {    print(error)  } else {    do {      let parsedData = try JsONSerialization.JsonObject(with: data!,options: []) as! [String:Any]      let currentConditions = parsedData["currently"] as! [String:Any]      print(currentConditions)      let currentTemperatureF = currentConditions["temperature"] as! Double      print(currentTemperatureF)    } catch let error as NSError {      print(error)    }  }}.resume()

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

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

编辑:

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

总结

以上是内存溢出为你收集整理的在Swift中正确解析JSON 3全部内容,希望文章能够帮你解决在Swift中正确解析JSON 3所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1058964.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存