gpt4 book ai didi

json - 尝试解析 JSON 值时出错

转载 作者:行者123 更新时间:2023-11-28 15:12:28 24 4
gpt4 key购买 nike

我在尝试访问 JSON 数据时遇到错误:

错误:

Cannot subscript a value of type [[String: Any]] with an index of type 'String'

这是我的代码:

    func parseData() {

fetchedExercise = []

let url = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"

let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

let task = session.dataTask(with: request) { (data, response, error) in

if error != nil {
print("error")
}
else {

do {
if let data = data,
let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
let exercises = fetchedData["results"] as? [[String: Any]] {

for eachExercise in exercises
{
if let name = exercises["name"] as? String, let description = exercises["description"] as? String { // Cannot subscript a value of type [[String: Any]] with an index of type 'String'
fetchedExercise.append(Exercise(name: name, description: description))
}
}
}
}
catch {
print("error")
}
}
}
task.resume()
}

我已在代码注释中显示错误所在的行。

最佳答案

尝试更改行:

if let name = exercises["name"] as? String, let description = exercises["description"] as? String {

到:

if let name = eachExercise["name"] as? String, let description = eachExercise["description"] as? String {

关于json - 尝试解析 JSON 值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47401549/

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