尝试解析JSON值时出错

时间:2017-11-20 21:39:38

标签: json swift api

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

错误:

  

不能使用索引类型下标类型为[[String:Any]]的值   '字符串'

这是我的代码:

    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()
}

我在代码注释中显示了错误。

1 个答案:

答案 0 :(得分:1)

尝试更改行:

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 {