获取JSON并在Swift中解析它?

时间:2017-06-09 00:24:19

标签: json swift get

我从url获取带有httpget请求的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变量的输出也是:

  

“[{” 标签 “:[” 的Firat “” kalkanı   operasyonu “ ”gazetehaberleri“]},{ ”标签“:[” 育空塞克   yargı“,”adliye“,”gazetehaberleri“]},{”标签“:[”foo“,”HüseyinAvni   Mutlu“,”HüseyinÇapkın“,”gazetehaberleri“]}]”

2 个答案:

答案 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 :(得分: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
    }
}