gpt4 book ai didi

json - 获取 JSON 并在 Swift 中解析它?

转载 作者:搜寻专家 更新时间:2023-11-01 05:34:22 26 4
gpt4 key购买 nike

我正在使用 httpget 请求从 url 获取 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"]}]"

最佳答案

首先只是关于您的代码的一些注释。将 URLRequest 转换为 URLRequest 是多余的。您需要使用 JSONSerialization jsonObject with data 方法将您的 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
}
}

关于json - 获取 JSON 并在 Swift 中解析它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447494/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com