https://github.com/ishkawa/APIKit ではJSONDataParserが提供されていますが、実装を見るとこのParserで返されるのはJSONをSwiftの世界の型に変換したものです。 (Dictionary, Array, String, etc...)
public func parse(data: Data) throws -> Any {
guard data.count > 0 else {
return [:]
}
return try JSONSerialization.jsonObject(with: data, options: readingOptions)
}
※JSONDataParserより抜粋
Codableに準拠した独自の型に変換するためには JSONDecoder().decode(Decodable.Protocol, from: Data)
を使用しますが、そのためにはData型を渡す必要があります。
なので、JSONDataParserは使用できず、そのままのDataを返す空のDataParserが必要です。
struct NopeDataParser: DataParser {
var contentType: String?
func parse(data: Data) throws -> Any {
data
}
}
これを用いると、以下のメソッドで取得できるobjectの型はDataになり、Codableに準拠した型に変換することができます。
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let data = object as? Data else { throw DomainError.parseFailed(object) }
return try JSONDecoder().decode(Response.self, from: data)
}