我有一段时间了解使用Swift 3的简单JSON序列化原则.我可以帮助解决从网站解码JSON到阵列所以我可以访问它作为jsonResult [“team1”] [“a”]等?这是相关代码:
let httprequest = URLSession.shared.dataTask(with: myurl){ (data,response,error) in self.label.text = "RESULT" if error != nil { print(error) } else { if let urlContent = data { do { let jsonResult = try JSONSerialization.jsonObject(with: urlContent,options: JSONSerialization.ReadingOptions.mutableContainers) print(jsonResult) //this part works fine print(jsonResult["team1"]) } catch { print("JSON Processing Failed") } } } } httprequest.resume()
传入的JSON是:
{ team1 = { a = 1; b = 2; c = red; }; team2 = { a = 1; b = 2; c = yellow; }; team3 = { a = 1; b = 2; c = green; }; }
谢谢
在Swift 3中,JSONSerialization.jsonObject(带有:options :)的返回类型已变为Any.
原文链接:https://www.f2er.com/swift/319993.html(您可以在Xcode的“快速帮助”窗格中查看它,并指向jsonResult.)
并且您不能为任何类型为Any的变量调用任何方法或下标.您需要显式类型转换才能使用Any.
if let jsonResult = jsonResult as? [String: Any] { print(jsonResult["team1"]) }
并且NSArray的默认元素类型,NSDictionary的默认值类型也变为Any. (所有这些东西简称为“id-as-Any”,SE-0116.)
因此,如果您想深入了解JSON结构,您可能需要一些其他显式类型转换.
if let team1 = jsonResult["team1"] as? [String: Any] { print(team1["a"]) print(team1["b"]) print(team1["c"]) }