【发布时间】:2018-02-28 20:18:46
【问题描述】:
【问题讨论】:
-
将字典解析成适当的 Codable 结构。
-
请将代码发布为文本而不是照片,这样人们可以直接将您的代码复制到游乐场并进行测试。
标签: ios swift nsdictionary unwrap
【问题讨论】:
标签: ios swift nsdictionary unwrap
嵌套只是意味着您的顶级 [String: Any] 字典中特定键的值是另一个 [String: Any] - 所以您只需将其转换为访问嵌套对象。
// assuming you have an object `json` of `[String: Any]`
if let pictureJSON = json["picture"] as? [String: Any] {
// if the JSON is correct, this will have a string value. If not, this will be nil
let nestedURL = pictureJSON["url"] as? String
}
我觉得我应该提一下,在 Swift 中序列化/反序列化 JSON 的过程与 Swift 4 中的 Codable 相比有了很大的飞跃。如果你有一个模型对象想要将此 JSON 映射到,那么整个事情都可以自动化离开(包括嵌套对象——你只需提供一个符合 Codable 的嵌套 Swift 结构/类)。 Here's some Apple documentation on it.
【讨论】:
这样:
if let picture = dictionary["picture"] as? [String:AnyObject] {
if let url = picture["url"] as? String {
}
if let width = picture["width"] as? Int {
}
}
【讨论】:
Any。大多数 Swift 类型都是结构。 AnyObject 只能用作类实例的具体类型。