2017-06-09 111 views
2

我使用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"]}]"

+0

您需要解析JSON字符串,並將其轉換爲一個字典。 有一些用於解析json的庫(你可以在github上搜索),我認爲在Foundation中也有一個內置解析器 https://developer.apple.com/swift/blog/?id=37 – hasen

+0

我不能'把json轉換成字典,你能幫我嗎? @LeoDabus –

+0

好的,我已經處理了它,但是,如何獲得標籤?因爲不能讓他們像jsonParsed [「標籤」]等... @LeoDabus –

回答

0

首先簡單介紹一下你的代碼。將URLRequest投射爲URLRequest是多餘的。您需要使用JSONSerialization JSONObject的數據方法來解析您的JSON數據到字典的數組:

let jsonString = "[{\"Tags\":[\"fırat\",\"kalkanı operasyonu\",\"gazetehaberleri\"]},{\"Tags\":[\"yüksek yargı\",\"adliye\",\"gazetehaberleri\"]},{\"Tags\":[\"foo\",\"Hüseyin Avni Mutlu\",\"Hüseyin Çapkın\",\"gazetehaberleri\"]}]" 

let data = Data(jsonString.utf8) 

let dictionaries = (try? JSONSerialization.jsonObject(with: data)) as? [[String:Any]] ?? [] 

for dict in dictionaries { 
    let tags = dict["Tags"] as? [String] ?? [] 

    for tag in tags { 
     print(tag) // fırat 
        // kalkanı operasyonu 
        // gazetehaberleri 
        // yüksek yargı 
        // adliye 
        // gazetehaberleri 
        // foo 
        // Hüseyin Avni Mutlu 
        // Hüseyin Çapkın 
        // gazetehaberleri 
    } 
} 
+0

非常感謝,它的工作原理! –

+0

不客氣 –

0

你的JSON輸出響應是在詞典[[String: Any]]

格式陣列所以解析它的簡單方法是

do { 
    // parse from data to array of dictionaries 
    if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] { 
     print(parsedData) 
    } 
} 
catch { 
    print(error) 
} 
+1

@LeoDabus謝謝,我改爲使用可選 – xmhafiz

+0

那麼我能做些什麼來獲取所有標籤?因爲print(parsedData [「Tags」])會發出如下錯誤:不能爲索引類型爲'String'的下標值'[[String:Any]]' –

+0

@CrisAngelordan將您當前的代碼添加到標籤中parsedData' – xmhafiz