This question already has answers here:
Correctly Parsing JSON in Swift 3
(8个答案)
三年前关闭。
我正在尝试将我的项目更新为swift 3.0,所有有关从服务器提取数据的代码在下图中都给出了这个错误。
json - 从服务器端提取数据数组期间,类型“Any”在Swift 3中没有下标成员-LMLPHP
我尝试了很多可用的解决方案,但没有得到有用的结果,在这种情况下有什么问题?
 do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)


        if let countries = json["Countries"] as? [String: AnyObject] {
            for country in countries {
                if let couname = country["countryname"] as? [AnyObject] {
                    country_names.append(couname)
                }

                if let coucode = country["code"] as? [AnyObject] {
                    country_codes.append(coucode)
                }

            }
        }
    } catch {
        print("Error Serializing JSON: \(error)")
    }

最佳答案

在使用前试着将json转换为[String: Any]
另外,您似乎也有一个错误:if let couname = country["countryname"] as? [AnyObject]
您应该将其转换为[String: AnyObject][[String: AnyObject]]
调整后的代码如下:

do {
    let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]

    if let countries = json["Countries"] as? [[String: AnyObject]] {
        for country in countries {
            if let couname = country["countryname"] as? [AnyObject] {
                country_names.append(couname)
            }

            if let coucode = country["code"] as? [AnyObject] {
                country_codes.append(coucode)
            }

        }
    }
} catch {
    print("Error Serializing JSON: \(error)")
}

10-07 19:13
查看更多