我正在尝试像这样解码 JSON。
这是我的数据模型
struct ResponseData: Decodable {
var AppointMentStatusId:Int!
var FromTime:String!
var ToTime:String!
var AppointmentDate: String!
var AppointMentStatus:String!
var DoctorFirstName:String!
var AppointmentId:Int!
var Rating:Float
var DoctorImage:String
enum CodingKeys: String, CodingKey {
case AppointMentStatusId
case FromTime
case ToTime
case AppointmentDate
case AppointMentStatus
case DoctorFirstName
case AppointmentId
case Rating
case DoctorImage
}
}
我还在 ResponseData 中设置了 init
struct Response:Decodable {
var Code:Int!
var Data2:String?
var Message:String!
var NoOfItems:String!
var Status:Bool!
var Data:[ResponseData]
enum CodingKeys: String, CodingKey {
case Code
case Data2
case Message
case NoOfItems
case Status
case Data
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
这段代码有问题
if let app = try container.decodeIfPresent([ResponseData].self, forKey: .Data) {// Problem is here
self.Data = app
}else{
self.Data = []
}
if let code = try container.decodeIfPresent(Int.self, forKey: .Code) {
self.Code = code
}else{
self.Code = 0
}
我已经设置了所有键的尝试
我正在尝试处理 Data 键的 nil 值。 当我得到 Data key is nil 时它工作正常 当我在数据键中获取数据时,它显示错误。
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "Data", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
这是我的 JSON 数据
{
"Code": 0,
"Status": true,
"Message": "Success",
"Data": [
{
"PatientUserID": 196,
"FirstName": "gaurav",
"MiddleName": "",
"LastName": "",
"PatientName": "gaurav ",
"MobileNo": "8585959585",
"EmailId": "gaurav.sainini@gmail.com",
"DOB": "2005-06-14T00:00:00",
"Gender": "Male",
"RegistrationId": 121,
"VisitId": null,
"FromTime": "8:00AM",
"ToTime": "8:15AM",
"AppointmentDateForComparison": "2019-07-20T00:00:00",
"AppointmentDate": "20-07-2019",
"AppointMentStatusId": 1233,
"AppointMentStatus": "Booked",
"DoctorId": 1,
"DoctorFirstName": "Dr.Doctor",
"Rating": 3.5,
"DoctorImage": "http://23.88.103.43:83/Assets/Icons/DoctorIcon/DefaultMale.png",
"AppointmentId": 250,
"MemberID": 126
}
],
"Data2": null,
"NoOfItems": null
}
请帮助我如何处理这个错误? 谢谢
最佳答案
完全删除 init 并使您的数据属性可选
var Data:[ResponseData]?
实际上,当我尝试您的初始化方法时,它工作正常。你如何解码?我就是这样做的。
let decoder = JSONDecoder()
do {
let result = try decoder.decode(Response.self, from: data)
print(result.Data)
} catch {
print(error)
}
关于json - 如何修复 "Expected to decode Dictionary<String, Any> but found an array instead"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57088686/