解析嵌套的JSON Swift 3 [英] Parse nested JSON Swift 3

查看:152
本文介绍了解析嵌套的JSON Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift 3中解析复杂的JSON文件.我在获取值时遇到了麻烦.我找到了一些示例代码,并尝试对其进行了一些调整,但是它不起作用.我当前收到错误消息:"Type"NSArray?"没有下标成员"...我什至不确定这是否是正确的方法它.附上JSON屏幕截图,以获取有关如何正确解析它的任何建议,对此深表感谢.

I'm trying to parse complex JSON file in Swift 3. I'm having trouble with getting values. I found some sample code and tried to tweak it a bit but it doesn't work I currently get an error "Type "NSArray?" has no subscript members"... I'm not even sure this is the right way to do it. Attaching JSON screenshot any advice on how to properly parse it really appreciated.

这是我当前的代码:

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

let mainlistJson = jsonResult["mainlist"]as? NSArray

if let items = mainlistJson["items"] as? NSArray 
{
for item in items {
 if let description = item["description"]as? String {
 print(description)
}  } }

推荐答案

在Swift中请勿使用NSArrayNSDictionary.您应该使用Swift标准库的数组和字典.

Don't use NSArray or NSDictionary in Swift. You should use the Arrays and Dictionaries of the Swift Standard Library.

对于数组,您可以使用:[Any]

For arrays, you could use: [Any]

对于词典:[String: Any]

然后,您将可以通过下标访问内容.

Then you will be able to access the contents via subscripts.

这篇关于解析嵌套的JSON Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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