[英]parse JSON Array from GET request Alamofire Swift 2
我是 Swift 的新手,我的任務是從 GET 請求中獲取數據並在 UI 上顯示其數據。 下面是我的代碼:
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, myUrl, headers: headers)
.responseJSON{ JSON in
if let jsonResult = JSON as? Array<Dictionary<String, String>> {
let title = jsonResult[0]["title"]
print(title)
}
}
我能夠通過請求獲取數據,但我不知道如何以某種格式(可能是 json 數組)解析JSON
對象,這些格式稍后可用於在 TableView 中顯示。 請幫忙
數據示例:
[ { "title": "Sony", "content": "Tech content", "image": "http://google.com/content/device.jpg?06" }, { "title": "Nexus" , "content": "Nexus 6 是一個新的開始", "image": "http://google.com/content/device.jpg?01" } ]
JSON 數據可以用不同的形式表示。 它可以編碼為字符串或轉換為平台上的已知數據類型。 json 的主要組成部分是數組、關聯數組(或字典)和值。
您正在顯示的 swift 結構如下所示。
這是一個數組。 此處顯示的數組內容以 [] 開頭和結尾,如 [1,2,3] 將是一個整數數組。
數組中的數據是字典列表。 字典以 {} 開頭和結尾。 喜歡 {"key":"value"}
這些字典包含鍵“標題”、“內容”和“圖像”。
因為您從 alamo 文件請求 responseJSON,您將返回一個已解析的結構,您需要做的就是像讀取普通數組和字典一樣讀取它,因為它就是這樣。
您應該閱讀有關如何制作使用上述邏輯的安全代碼的文檔。 http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.