1
votes

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.

1
Are you sure that is the json data you are receiving from your server? You have shown a null (which is fine for String?) but the error says you received a dictionary. You don't need the custom init; the default behaviour should do it for you.Paulw11
yeap I am receiving from server sideKkMIW
Could you instead of just catch { print(error) }, instead catch { print("Error while JSON decoding: \(error)" with response: \(String(data: data, encoding: .utf8))") }? You seem to think that's the JSON you are getting, but according to the error it's not, so print the JSON when it's failing.Larme

1 Answers

2
votes

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.