首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Speed2.0中解析JSON

在Speed2.0中解析JSON
EN

Stack Overflow用户
提问于 2015-07-23 16:54:51
回答 1查看 1.4K关注 0票数 0

我正在尝试解析来自服务器api的JSON数据。json:

代码语言:javascript
复制
    [
 {"interest": {
 "title":"Sport",
 "sub":[
        "painting",
        "photography",
        "museum"]
 }
 },
 {"interest": {
 "title": "music",
 "sub": [
         "rock",
         "classic",
         "techno"]
 }
 }]

从一个文件中获取它的代码只是为了测试来解析它:

代码语言:javascript
复制
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)
        }

我可以通过以下方式访问整个文件:

代码语言:javascript
复制
print(jsonResult)

但是我不能访问一个以上的级别,这里是第一个级别:

代码语言:javascript
复制
if let a = jsonResult {

        print(a[0]["interest"])
    }

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

代码语言:javascript
复制
    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这样的框架。

非常感谢!本

编辑:

解决(谢谢@maxpovver):

代码语言:javascript
复制
//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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-23 17:31:16

答案

代码语言:javascript
复制
//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

还可以使其更具可读性:

代码语言:javascript
复制
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

如果没有额外的库,您就永远不可能简化这个问题,因为斯威夫特不支持动态类型。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31593594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档