gpt4 book ai didi

json - 错误 : Type 'Any' has no subscript members AlamoFire with Swift 4

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

我尝试了很多解决方案,但都没有成功。我正在尝试传递我的 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 之前的解决方案均无效,我无法弄明白。

Image

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

最佳答案

你需要

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

正确的是

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

关于json - 错误 : Type 'Any' has no subscript members AlamoFire with Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288876/

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