在Swift 2.0中解析JSON

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

我正在尝试从服务器api解析JSON数据. json:

I'm trying to parse JSON data from a server api. The json :

[ {"interest": { "title":"Sport", "sub":[ "painting", "photography", "museum"] } }, {"interest": { "title": "music", "sub": [ "rock", "classic", "techno"] } }]

从文件中获取代码以进行测试以分析它的代码:

The code to get it from a file just to test to parse it :

do{ let path = NSBundle.mainBundle().pathForResource("MainInterest", ofType: "json") let jsonData = NSData(contentsOfFile: path!) let jsonResult:NSArray! = try NSJSONSerialization.JSONObjectWithData(jsonData! , options: NSJSONReadingOptions.MutableContainers) as! NSArray } catch let error as NSError { print(error) }

我可以使用:

print(jsonResult)

但是我不能访问多个级别,这是第一个级别:

But I can't access more than one level, here is the first level :

if let a = jsonResult { print(a[0]["interest"]) }

然后我可以从文件中获取第一个对象,但是我想访问 jsonResult [0] ["interest"] ["title"](== Sport)或jsonResult [0 ] ["interest"] ["sub"] [2](==摄影),但是我的这种错误构建失败:

I can then get my first object from my file, but I would like to access jsonResult[0]["interest"]["title"] (==Sport) or jsonResult[0]["interest"]["sub"][2] (== photography) but I have this kind of error build failed:

Cannot subscript a value of type 'AnyObject?!' with an index of type 'String' Cannot subscript a value of type 'AnyObject?!' with an index of type 'Int'

能请你帮我吗?我真的很困惑,我认为苹果文档在这一点上不是很明确.而且我不想使用swiftyJson等框架.

Could you please help me ? I'm really stuck and the apple doc is not so explicite on this point I think. And I don't want to use framework like swiftyJson etc.

非常感谢! 本

已解决(感谢@maxpovver):

Solved with (thanks @maxpovver) :

//To Get Title let title = (((self.interests as NSArray)[0] as? NSDictionary)?["interest"] as? NSDictionary)?["title"] as? NSString print(title) //To Get Sub let sub = ((((self.interests as NSArray)[0] as? NSDictionary)?["interest"] as? NSDictionary)?["sub"] as! NSArray)[1] as! NSString

推荐答案

答案

//To Get Title let title = (((self.interests as Array)[0] as? Dictionary)?["interest"] as? Dictionary)?["title"] as? String print(title) //To Get Sub let sub = ((((self.interests as Array)[0] as? Dictionary)?["interest"] as? Dictionary)?["sub"] as! Array)[1] as! String

还可以提高可读性:

let firstInterest = ((self.interests as Array)[0] as? Dictionary)?["interest"] as? Dictionary)? let title = firstInterest?["title"] as? String let sub = (firstInterest?["sub"] as! Array)[1] as! String

如果没有一些额外的库,因为swift不支持动态类型,您将永远无法简化.

You'll never be ablo to simplify that without some extra libraries as swift does not support dynamic types.

更多推荐

在Swift 2.0中解析JSON

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

发布评论

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

>www.elefans.com

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