我使用httpget請求從url獲取json文件。然後,我想將所有來自json的標籤打印到屏幕上。然而,我使用這個代碼來做到這一點,我不能這樣做。你可以幫我嗎?獲取JSON並在Swift中解析它?
夫特3代碼:
let url:URL = URL(string: "https://api.hurriyet.com.tr/v1/articles...deleted...")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
for tags in data{
for tag in tags["Tags"]{
print(tag)
}
}
}
task.resume()
例JSON輸出和dataString變量的輸出也:
"[{"Tags":["fırat","kalkanı operasyonu","gazetehaberleri"]},{"Tags":["yüksek yargı","adliye","gazetehaberleri"]},{"Tags":["foo","Hüseyin Avni Mutlu","Hüseyin Çapkın","gazetehaberleri"]}]"
您需要解析JSON字符串,並將其轉換爲一個字典。 有一些用於解析json的庫(你可以在github上搜索),我認爲在Foundation中也有一個內置解析器 https://developer.apple.com/swift/blog/?id=37 – hasen
我不能'把json轉換成字典,你能幫我嗎? @LeoDabus –
好的,我已經處理了它,但是,如何獲得標籤?因爲不能讓他們像jsonParsed [「標籤」]等... @LeoDabus –