2016-09-18 69 views
1

我试图访问[ “上限类别”] [ “第一类”] [0] [0]本地JSON文件的无法从JSON访问嵌套的字典/阵列,迅速

{ 
    "upper category": { 
     "first category": [ 
      [ 
       "this is a question", 
       "this is an answer", 
       "this is the rank" 
      ], 
      [ 
       "this is a question2", 
       "this is an answer2", 
       "this is the rank2" 
      ] 
     ], 
     "second category": [ 
      [ 
       "this is a question3", 
       "this is an answer3", 
       "this is the rank3" 
      ] 
     ] 
    } 
} 

let path = Bundle.main.path(forResource: "data", ofType: "json") 
do {let data:NSData = try NSData(contentsOfFile: path!) 
    let json = try? JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 

我无法访问超出第一个字典的任何内容。

我试了几次有类似的选项(我试过多个旧的解决方案,但他们似乎并没有为我工作,也许迅疾3)

if let description = ((((json?["upper category"] as? AnyObject)?["first category"] as? AnyObject)?[0] as? AnyObject)?[0] as? String) { 

这可能是一个noob问题,我是新来的IOS。虽然任何答案非常赞赏,解释如何编写代码,嵌套类型的其他数将是最好

(Xcode中8,快捷3)

回答

1

这是一个有点矫枉过正,但你可以投的JSON来[String:[String:[[String]]]]

let json = try? JSONSerialization.jsonObject(...) as? [String:[String:[[String]]]] 
+0

Thx它的作品,这是否被认为是一个很好的做法? – temo