1

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.

3
  • 2
    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. Commented Jan 26, 2021 at 10:16
  • yeap I am receiving from server side Commented Jan 26, 2021 at 10:24
  • 1
    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. Commented Jan 26, 2021 at 10:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.