在Swift 2.0中解析JSON [英] Parsing JSON in swift 2.0

查看:99
本文介绍了在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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