我没有运气就尝试了许多解决方案。我正在尝试传递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";
}
答案 0 :(得分: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)
}
}
}
正确的是
{“ Data”:[{“ DisplayName”:“ Jerry Smith”,“ DOB”:“ 09/08/1987”}]}