简体   繁体   中英

Swift JSONDecoder type mismatch on parsing ISO8601 DateInterval

I'm trying to parse next sample DateInterval values an Api suplies following ISO 8601 format:

[
    {"ISO8601":"PT10M","text":"time: 00:10"},
    {"ISO8601":"PT1H10M","text":"time: 01:10"},
    {"ISO8601":"PT3H20M","text":"time: 03:20"}
]

to next model:

struct DTOTest:Codable {
    var ISO8601:DateInterval
    var text:String
}

But I get next mismatch exception:

Type 'Dictionary' mismatch Context: Expected to decode Dictionary but found a string/data instead. CodingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "ISO8601", intValue: nil)]

Mi decoding function uses 8601 strategy, so it should read it properly, and indeed it works Ok with ISO 8601 Date:

static func decode<T:Decodable>(data:Data, completion: @escaping (Result<T,NetworkError>) -> Void) {

    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601

    do {
        let retval = try decoder.decode(T.self, from: data)
        completion(.success(retval))

    } catch let DecodingError.typeMismatch(type, context)  {
        var reason = "Type '\(type)' mismatch"
        reason += "\nContext: \(context.debugDescription)"
        reason += "\nCodingPath: \(context.codingPath)"
        completion(.failure(.requestError(reason: reason)))
    } catch {
        let reason = "Error '\(error.localizedDescription)'"
        completion(.failure(.requestError(reason: reason)))
    }

}

What may be missing here?

The iso8601 date decoding strategy supports only the format yyyy-MM-dd'T'HH:mm:ssZ to decode String to Date .

It's impossible to decode an ISO8601 string directly to DateInterval with JSONDecoder anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM