【问题标题】:Error: Type 'Any' has no subscript members AlamoFire with Swift 4错误:类型 'Any' 没有下标成员 AlamoFire 与 Swift 4
【发布时间】:2019-01-21 11:20:09
【问题描述】:

我尝试了许多解决方案,但都没有成功。我正在尝试传递我的 json 数据并返回用户值。

型号:

import Foundation

class UserModel: NSObject {

var UserID: String!
var Name: String!

init(UserID: String, Name: String) {
    super.init()

    self.UserID = UserID
    self.Name = Name

}
}

获取功能:

    guard let url = URL(string: "https://api.com/api.php?PatientList") else { return }
    var request = URLRequest(url: url)

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"

    let pinPost = "&Token=\(token)"
    request.httpBody = pinPost.data(using: .utf8)

    Alamofire.request(request).responseJSON { (response) in
        if let dict = response.result.value as? Dictionary<String, AnyObject> {
            if let datas = dict["Data"] as? NSArray {
                for data in datas {

                    let users = UserModel(UserID: data["PatientID"], Name: data["DisplayName"])

                }
            }
        }
    }

我收到Type 'Any' has no subscript members 的错误消息,以前的解决方案没有奏效,我无法弄清楚。

 ["Response": 1, "Data": <__NSSingleObjectArrayI 0x600002624ae0>(
 <__NSArrayI 0x600002455f60>(
 {
DOB = "09/08/1987";
DisplayName = "Jesse Gray";
PatientID = "1575da84-864f-11e8-9bae-02bd535e30bc";
}

【问题讨论】:

    标签: json swift alamofire


    【解决方案1】:

    你需要

    if let datas = dict["Data"] as? [[String:Any]] {
    

    而不是

    if let datas = dict["Data"] as? NSArray {
    

    因为数组元素是 Any 类型,不能在这里订阅 data["PatientID"]data["DisplayName"]

    Alamofire.request("request").responseJSON { (response) in
        if let dict = response.result.value as? [String:Any] {
            if let datas = dict["Data"] as? [[String:Any]] {
                for data in datas {
                    if let id = data["PatientID"] as? Int , let name = data["DisplayName"] as? String {
                      let users = UserModel(UserID:id, Name: name)
                    } 
                }
            }
        }
    }
    

    还可以考虑使用Codable 来解析响应

    struct Root: Codable {
        let data: [UserModel]
        enum CodingKeys: String, CodingKey {
           case data = "Data"
        }
    }
    
    struct UserModel: Codable {
        let patientID: Int
        let displayName: String
    
        enum CodingKeys: String, CodingKey {
            case patientID = "PatientID"
            case displayName = "DisplayName"
        }
    }
    
    Alamofire.request("request").responseData{ (response) in
        if let data = response.data  {
    
            do {
                let res = try JSONDecoder().decode(Root.self, from: data)
                print(res.data)
            }
            catch {
                print(error)
            }
        }
    }
    

    正确的是

    { "数据" : [{"DisplayName":"Jerry Smith","DOB":"09/08/1987"}] }

    【讨论】:

    • 我在尝试使用Codable 解决方案时遇到此错误:dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.})))
    • 那么你的json无效
    • 我已经添加了我的 json 的照片,请你看一下。
    • 把它作为字符串发布,我会让你知道正确的
    • 查看编辑,也没有 PatientID 键所以用 DOB 替换它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多