{ "expertPainPanels" : [ { "name": "User A","organization": "Company A" },{ "name": "User B","organization": "Company B" } ]}
我正在尝试使用Swift 3获取此数据.
if (statusCode == 200) { do{ let Json = try? JsONSerialization.JsonObject(with: data!,options:.allowFragments) // [[String:AnyObject]]/* If I do this: let Json = try? JsONSerialization.JsonObject(with: data!,options:.allowFragments) as! [String:Any] if let experts = Json?["expertPainPanels"] as! [String: Any] { I get "Initializer for conditional binding must have Optional type,not '[String: Any]'"*/ // Type 'Any' has no subscript members. if let experts = Json["expertPainPanels"] as? [String: AnyObject] { for expert in experts { let name = expert["name"] as? String let organization = expert["organization"] as? String let expertPainPanel = ExpertPainPanel(name: name,organization: organization)! self.expertPainPanels += [expertPainPanel] self.tableVIEw.reloadData() self.removeLoadingScreen() } } }catch { print("Error with Json: \(error)") } }
它在Swift 2中运行良好.我更新了Swift 3,它破坏了代码.我读过几篇SO,但我仍然很难理解它.我应用了一些建议,包括JSON Parsing in Swift 3,但我仍然无法修复我得到的错误.
从Swift 3开始,你需要尽早进行演员表演.这一行:
let Json = try? JsONSerialization.JsonObject(with: data!,options:.allowFragments)
应该成为这样的:
let Json = try JsONSerialization.JsonObject(with: data!,options:.allowFragments) as? [String : AnyObject]
这是因为JsONSerialization现在返回Any,它没有为[]运算符实现变体.确保您安全地展开演员,并采取常见措施,以确保您不会崩溃你的程序.
编辑:您的代码应该或多或少看起来像这样.
let data = Data()let Json = try JsONSerialization.JsonObject(with: data,options:.allowFragments) as! [String : AnyObject]if let experts = Json["expertPainPanels"] as? [String: AnyObject] {总结
以上是内存溢出为你收集整理的使用Swift 3解析JSON全部内容,希望文章能够帮你解决使用Swift 3解析JSON所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)