Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

ios - Trying to parse Json data into model Class this getting error while using codable

Trying to parse Json data into Model Class "TimeSheetModel" I am getting below error.

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "error", intValue: nil)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))

Response Data Json

{
    "code": 200,
    "message": null,
    "error": null,
    "data": {

    }
}

// MARK: - TimeSheetModel

struct TimeSheetModel: Codable {
    
    let code: Int?
    let message: String?
    let error: String?
    let timeSheetModel_Data: TimeSheetModel_Data?

    enum CodingKeys: String, CodingKey {

        case code = "code"
        case message = "message"
        case error = "error"
        case timeSheetModel_Data = "data"

    }

    init(from decoder: Decoder) throws {

        let values = try decoder.container(keyedBy: CodingKeys.self)
        code = try values.decodeIfPresent(Int.self, forKey: .code)
        message = try values.decodeIfPresent(String.self, forKey: .message)
        error = try values.decodeIfPresent(String.self, forKey: .error)
        timeSheetModel_Data = try values.decodeIfPresent(TimeSheetModel_Data.self, forKey: .timeSheetModel_Data)


    }
}

May be I have to handling if else coding for string and Int inside codable model class.

question from:https://stackoverflow.com/questions/65899325/trying-to-parse-json-data-into-model-class-this-getting-error-while-using-codabl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As error says: let error: String? error property is expected to be a String type - but server returns a Dictionary there.

The JSON you posted seems to have null there, but probably error is shown due to different JSON data - one that has error object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...