Reputation: 433
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..)
//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
{
data: [
{
id: 2,
title: "Hunger Games",
cover: "http://example.com",
genre: 2
}
]
}
Help!
Upvotes: 25
Views: 44412
Reputation: 1254
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.
Upvotes: 4
Reputation: 12190
Here is how you can process a given 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.
Upvotes: 49