[英]Swift JSONDecoder type mismatch on parsing ISO8601 DateInterval
I'm trying to parse next sample DateInterval values an Api suplies following ISO 8601 format:我正在尝试按照 ISO 8601 格式解析 Api suplies 的下一个示例 DateInterval 值:
[
{"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)]
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: Mi解码功能使用8601策略,所以它应该正确读取它,并且确实可以与ISO 8601一起使用 日期:
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
. iso8601
日期解码策略仅支持格式yyyy-MM-dd'T'HH:mm:ssZ
将String
解码为Date
。
It's impossible to decode an ISO8601 string directly to DateInterval
with JSONDecoder
anyway.无论如何,都不可能使用
JSONDecoder
将 ISO8601 字符串直接解码为DateInterval
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.