Search code examples
jsonswiftjsondecoder

How to fix error "mismatch" in Xcode while trying to decode JSON


I'm new to Swift language and I'm trying to build a simple JSON parsing App in Xcode.

Here's an error I get: typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "Date", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))

Here's a link a want to parse: https://www.cbr-xml-daily.ru/daily_json.js

What model do I have for it: (I used https://app.quicktype.io for creating it)

struct Welcome: Codable {
    var date, previousDate: Date
    var previousURL: String
    var timestamp: Date
    var valute: [String: Valute]

    enum CodingKeys: String, CodingKey {
        case date = "Date"
        case previousDate = "PreviousDate"
        case previousURL = "PreviousURL"
        case timestamp = "Timestamp"
        case valute = "Valute"
    }
}

struct Valute: Codable {
    var id, numCode, charCode: String
    var nominal: Int
    var name: String
    var value, previous: Double

    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case numCode = "NumCode"
        case charCode = "CharCode"
        case nominal = "Nominal"
        case name = "Name"
        case value = "Value"
        case previous = "Previous"
    }
}

And here's a code for parsing and decoding:

func request(urlString: String, completion: @escaping (Welcome?, Error?) -> Void) {
    guard let url = URL(string: urlString) else { return }
    
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print("Some error")
            completion(nil, error)
            return
        } else {
            guard let data = data else { return }
            do {
                let welcome = try JSONDecoder().decode(Welcome.self, from: data)
                completion(welcome, nil)
            } catch let jsonError {
                print("Failed to decode JSON: \(jsonError)")
                completion(nil, jsonError)
            }
            
        }
    } .resume()
}

Will be really grateful for any help/advice.


Solution

  • This is because you're not decoding Date properly.

    Try setting dateDecodingStrategy for your JSONDecoder:

    do {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        let welcome = try decoder.decode(Welcome.self, from: data)
        completion(welcome, nil)
    } catch let jsonError {
        print("Failed to decode JSON: \(jsonError)")
        completion(nil, jsonError)
    }