Swift 3的JSONSerialization

编程入门 行业动态 更新时间:2024-10-27 13:30:10
本文介绍了Swift 3的JSONSerialization的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有时间了解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

本文发布于:2023-11-26 04:45:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   JSONSerialization

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!