嵌套只意味着顶级[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 {
}
}