-1

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?

Asperi
  • 228,894
  • 20
  • 464
  • 690
Matias Masso
  • 1,670
  • 3
  • 18
  • 28

1 Answers1

1

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks Vadian, I'll have to build a parser from String then – Matias Masso Apr 02 '20 at 17:15
  • 1
    Consider also that `DateInterval` is a struct with start date and end date or duration, you probably mean `TimeInterval` which represents only a duration according to the ISO8601 string. – vadian Apr 02 '20 at 17:25
  • Yes, TimeInterval was my first option, but it is expressed in seconds and as far as I know JSONDecoder does not parse it from ISO8601 either. The goal is to read ISO8601 interval dates and offer the user a time picker to edit them – Matias Masso Apr 02 '20 at 17:36
  • `PT1H10M` is a duration of 70 seconds. The ISO8601 *interval* syntax requires at least a start date. – vadian Apr 02 '20 at 17:46
  • PT1H10M is indeed a duration of 70 minutes according to ISO8601 syntax. I finally built a parser from scratch for TimeInterval. Thanks for your clues. – Matias Masso Apr 06 '20 at 15:57