Samah Ahmed Samah Ahmed - 1 month ago 7
JSON Question

Type "Any" has no subscript members in Swift 3 during pulling array of data from server

I'm trying to update my project to swift 3.0 and all codes about pulling data from server is give me this error in the following picture.

enter image description here

I tried a lot of solutions that is available here but with no useful result what is the problem in this case ?

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

Answer

Try casting json to [String: Any] before using it.

Also you seem to have an error here: if let couname = country["countryname"] as? [AnyObject]

You should cast it to an array of [String: AnyObject]: [[String: AnyObject]]

The adjusted code would look like:

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