[英]Can't access nested dictionaries/arrays from json with swift
我试图访问本地json文件的[“上类别”] [“第一类”] [0] [0]
{
"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,swift 3)
这有点矫枉过正,但你可以将json转换为[String:[String:[[String]]]]
let json = try? JSONSerialization.jsonObject(...) as? [String:[String:[[String]]]]
否则,例如,如果字典包含嵌套字典以外的元素,则只需将顶级字典转换为[String:Any]
并单独转换嵌套元素。
if let json = try? JSONSerialization.jsonObject(...) as? [String:Any] {
let foo = json["foo"] as? Int
let bar = json["bar"] as? [String:Any]
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.