ios Swift - 如何遍历 NSDictionary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24764755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - How to loop through NSDictionary
提问by Mahi008
Hi I'm currently learning Swift, and I wanted to extract data from a JSON Api, My Swift code looks like this. To be specific, I need to extract each and every key and its value,(for example: print the value of title, cover etc..)
嗨,我目前正在学习 Swift,我想从 JSON Api 中提取数据,我的 Swift 代码如下所示。具体来说,我需要提取每个键及其值,(例如:打印标题、封面等的值。)
//Json request
var error: NSError?
var raw = NSString.stringWithString("http://example.com/MovieAPI/api/v1/movies/")
var api_url = NSURL.URLWithString(raw)
let jsonData: NSData = NSData.dataWithContentsOfURL(api_url, options: nil, error: &error)
let result = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)
as NSDictionary
for val in result {
for (var i=0; i < val.value.count; i++){
//println(val.value.valueAtIndex(3)) Not Working
}
}
and the structure of my JSON is
我的 JSON 结构是
{
data: [
{
id: 2,
title: "Hunger Games",
cover: "http://example.com",
genre: 2
}
]
}
Help!
帮助!
回答by Keenle
Here is how you can process a given JSON:
以下是处理给定 JSON 的方法:
let dataArray = result["data"] as NSArray;
print("Data items count: \(dataArray.count)")
for item in dataArray { // loop through data items
let obj = item as NSDictionary
for (key, value) in obj {
print("Property: \"\(key as String)\"")
}
}
Remarks:
评论:
Remember that you receive parsed objects as NSDictionary
and when you iterate through the dictionary, order in which you receive properties may differ from the order in the original JSON.
请记住,NSDictionary
当您遍历字典时,您会收到已解析的对象,您收到属性的顺序可能与原始 JSON 中的顺序不同。
回答by AppsWise
Check this piece of code for reference:
检查这段代码以供参考:
// MARK: - Firebase
func retrieveData(){
ref.observe(FIRDataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as! [String : AnyObject]
let contactList = postDict["contacts"]!
let user = FIRAuth.auth()!.currentUser
let contactArray = contactList[user!.uid]! as! NSDictionary
for (key,_) in contactArray {
let contact:NSObject = contactArray[key] as! NSObject
let firstName:String! = contact.value(forKey: "firstName") as? String
let lastName:String! = contact.value(forKey: "lastName") as? String
let company:String! = contact.value(forKey: "company") as? String
let phone:String! = contact.value(forKey: "phone") as? String
let email:String! = contact.value(forKey: "email") as? String
print(contact.value(forKey: "firstName")!)
contacts.append(Contact(firstName:firstName, lastName: lastName, company: company, phone: phone, email: email))
}
self.tableView.reloadData()
})
}
It specially gets tricky when you parse the key value into the usable object that is where the NSObject comes to rescue so that you can get the values for key.
当您将键值解析为可用对象时,它会变得特别棘手,这是 NSObject 拯救的地方,以便您可以获取键的值。