我有时间了解Swift 3的简单JSON序列化原理,请问可以从网站将JSON解码为数组的过程中获得一些帮助,以便以jsonResult["team1"]["a"]的身份进行访问吗?这是相关代码:
I am having a bear of a time understanding simple JSON serialization principles with Swift 3. Can I please get some help with decoding JSON from a website into an array so I can access it as jsonResult["team1"]["a"] etc? Here is relevant code:
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(with:options:)的返回类型已变为Any.
In Swift 3, the return type of JSONSerialization.jsonObject(with:options:) has become Any.
(您可以在Xcode的快速帮助"窗格中将其指向jsonResult进行检查.)
(You can check it in the Quick Help pane of your Xcode, with pointing on jsonResult.)
并且您不能为类型为Any的变量调用任何方法或下标.您需要显式类型转换才能使用Any.
And you cannot call any methods or subscripts for the variable typed as Any. You need explicit type conversion to work with Any.
if let jsonResult = jsonResult as? [String: Any] { print(jsonResult["team1"]) },默认的元素类型为NSArray,默认的值类型为NSDictionary,也已变为Any. (所有这些东西都简称为"id-as-Any", SE-0116 .)
And the default Element type of NSArray, the default Value type of NSDictionary have also become Any. (All these things are simply called as "id-as-Any", SE-0116.)
因此,如果您想更深入地了解JSON结构,则可能需要进行其他一些显式的类型转换.
So, if you want go deeper into you JSON structure, you may need some other explicit type conversion.
if let team1 = jsonResult["team1"] as? [String: Any] { print(team1["a"]) print(team1["b"]) print(team1["c"]) }更多推荐
Swift 3的JSONSerialization
发布评论