我需要獲得最新的"id": "article"
"createdAt": "2016-04-22T03:38:39.130Z"
日期。我如何才能迅速從請求中獲取這些數據?
注意:對不起,我是一個快捷的新手。
我需要獲得最新的"id": "article"
"createdAt": "2016-04-22T03:38:39.130Z"
日期。我如何才能迅速從請求中獲取這些數據?
注意:對不起,我是一個快捷的新手。
let url = "https://cdn.contentful.com/spaces/maz0qqmvcx21/entries?access_token=ae8163cb8390af28cd3d7e28aba405bac8284f9fe4375a605782170aef2b0b48";
var jsonData:NSData?
do{
jsonData = try NSData(contentsOfURL: NSURL(string: url)!, options: NSDataReadingOptions.DataReadingUncached)
let jsonObject:AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments)
if let itemArray = jsonObject?.objectForKey("items") as? NSArray{
for item in itemArray{
if let sysItem = item.objectForKey("sys"){
//this is createdAt
if let createdAt = sysItem.objectForKey("createdAt") as? String{
print("createdAt:\(createdAt)")
}
if let contentTypeItem = sysItem.objectForKey("contentType")!.objectForKey("sys"){
//this is id
if let id = contentTypeItem.objectForKey("id") as? String{
print("id:\(id)")
}
}
}
}
}
}catch let err as NSError{
print("err:\(err)")
}
此代碼沒有使用任何庫,但可以使用SwiftyJSON,這將很容易解析json。
希望得到這個幫助。
謝謝!解決了我的問題:)。 – kevinabraham
這可以用簡單的方法完成。我假設你已經解析了你的json到字典
你有一個關鍵字,它是一個字典數組,並且在這個字典中你創建了at和id(它深入到層次結構中,但我會告訴你如何得到它)鑰匙。您只需執行此操作即可訪問它。
for dict in jsonDict["items"] as! Array<NSDictionary> {
let sysDict = dict["sys"] as! NSDictionary
print(sysDict["createdAt"]) //prints all createdAt in the array
let contentDict = sysDict["contentType"]
print((contentDict["sys"] as! NSDictionary)["id"]) // prints all ids
}
希望這會有所幫助。
應該試試SwiftyJSON – Jing