[英]Multidimensional array/dictionary loop in Swift
我正在尝试遍历我从JSON字符串中获得的多维数组/字典。 最初我来自PHP,所以我的方法可能有点偏离。
我的问题是我似乎无法进入子数组/字典。
到目前为止,我的代码:
func getJSON(){
let url = NSURL(string: url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!)
let array = jsonObj!.allKeys
for keys in array {
print(keys)
}
OperationQueue.main.addOperation({
//Nothing to do right now
})
}
}).resume()
}
我的JSON:
{
"ArrayName1": {
"info": "This is my first array!",
"more": "Even more info!"
},
"ArrayName2": {
"info": "This is my second array!",
"more": "Even more info about the second array!"
}
}
该函数会打印出很好的键(例如ArrayName1),但是如何深入数组呢? 要打印“信息”?
如果您确定它是[String:[String:Any]]形式的字典,则可能需要尝试一下。
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: [String: Any]] {
let array = jsonObj!.allKeys
for key in array {
print(key)
let info = jsonObj[key]["info"] as! String
}
}
NSURL
。有一个本机结构URL
。 .allowFragments
毫无用处,因为JSON显然是集合类型。 NSDictionary
,而要使用本机类型Dictionary
。 所有集合类型都是字典。 使用快速枚举来解析键和值。 所有键和值都是字符串。
func getJSON(){
let url = URL(string: url)!
URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
if error != nil {
print(error!)
return
}
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:[String:String]] {
for (key, innerDictionary) in jsonObj {
print(key)
if let info = innerDictionary["info"] {
print("info", info)
}
}
DispatchQueue.main.async {
//Nothing to do right now
}
} else { print("The JSON object is not [String:[String:String]]") }
} catch {
print(error)
}
}).resume()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.