如何解决“预期对Dictionary <String,Any>进行解码,但找到一个数组代替”?

时间:2019-07-18 06:56:03

标签: json swift decodable

我正在尝试像这样解码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中设置了初始化

 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值。 当我得到数据键为零时,它工作正常 当我在数据密钥中获取数据时,显示错误。

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
}

请帮助我如何处理此错误? 谢谢

2 个答案:

答案 0 :(得分:1)

完全删除该初始化,并将您的Data属性设置为可选

var Data:[ResponseData]?

实际上,当我尝试使用您的init方法时,它可以正常工作。您如何解码?这就是我的方法。

let decoder = JSONDecoder()
do {
    let result = try decoder.decode(Response.self, from: data)
    print(result.Data)
} catch {
    print(error)
}

答案 1 :(得分:0)

不必使用override init(from decoder: Decoder)方法并编写enum CodingKeys。如果密钥相同,则应该自动解码。