2017-05-31 148 views
-3

我做POST請求,我得到這個響應訪問嵌套的字典迅速3

{ 
    "id": "6QRqYlqpv", 
    "hostname": "twitter.com", 
    "link": "https://twitter.com/AliNatham/status/869551271409328129", 
    "title": "869551271409328129", 
    "filename": "869551271409328129.mp4", 
    "originalFormat": "mp4", 
    "originalType": "video", 
    "formats": [ 
    { 
     "format": "mp4", 
     "type": "video", 
     "url": "https://loadercdn.io/download?id=6QRqYlqpv&format=mp4", 
     "directUrl": "https://loadercdn.io/download?id=6QRqYlqpv&direct=true&format=mp4", 
     "directUrl_": "directUrl will be deprecated soon, do not use", 
     "filename": "869551271409328129.mp4" 
    }, 
    { 
     "format": "avi", 
     "type": "video", 
     "url": "https://loadercdn.io/download?id=6QRqYlqpv&format=avi", 
     "directUrl": "https://loadercdn.io/download?id=6QRqYlqpv&direct=true&format=avi", 
     "directUrl_": "directUrl will be deprecated soon, do not use", 
     "filename": "869551271409328129.avi" 
    }] 
} 

我試圖訪問「格式」:「MP4」像這樣 打印(JSON [「格式」] [「網址「] as any) 但我得到零

+0

你用什麼來解析json到swift? – pableiros

+0

guard讓json =試試JSONSerialization.jsonObject(with:data,options:[])as? [String:AnyObject] else {return} – Rioodi

回答

0

您的formats是一個數組。您需要先訪問陣列中的嵌套對象,然後訪問url

嘗試print(json["formats"][0]?["url"] as Any)

0

我解決它!

let formats = json["formats"] as! Array<[String:AnyObject]> 
print(test[0]["url"] as! String) 
+0

這是一個不好的解決方案。它假定'formats'至少有1個元素,它假定你想要的值是第一種格式。情況並非總是如此。 – rmaddy