如何在Swift中操作嵌套字典,例如JSON数据? [英] How do I manipulate nested dictionaries in Swift, e.g. JSON data?

查看:715
本文介绍了如何在Swift中操作嵌套字典,例如JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSJSONSerialization在Swift应用程序中解析JSON.但是,返回的字典由复杂的,深层嵌套的结构组成,因此很难使用非常长的类型声明(例如Dictionary<String, Array<Dictionary<String, ....>>).

I'm using NSJSONSerialization to parse JSON in a Swift application. However, the returned dictionary consists of a complicated, deeply nested structure, making it impractical to have very long type declarations (e.g. Dictionary<String, Array<Dictionary<String, ....>>).

在Swift中是否有一种很好的方法来处理这种结构,因为它的集合结构非常复杂并且其类型直到运行时才知道?

Is there a good way of working with such a structure in Swift, where the collection's structure is very complicated and its types aren't known until runtime?

推荐答案

只需获取对您的json数据的引用作为NSDictionary:

Just grab a reference to your json data as an NSDictionary:

var dict: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

然后您可以使用下标引用它:

then you can reference it using subscripts:

var myValue: NSString = dict["level1"]["level2"]

这篇关于如何在Swift中操作嵌套字典,例如JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆