我有以下结构,响应解析失败,因为 url (https://example.url.com/test a
) 中有一个空格。如何在反序列化层中使用 %20 值对其进行转义并将其保留为 URL 类型?
struct Response: Decodable {
let url: URL
enum CodingKeys: String, CodingKey {
case url
}
init(from decoder: Decoder) throws {
self.url = try decoder.container(keyedBy: CodingKeys.self).decode(URL.self, forKey: .url)
}
}
let string = "{\"url\":\"https://example.url.com/test a\"}"
let responseModel = try? JSONDecoder().decode(Response.self, from: string.data(using: .utf8)!)
print(responseModel?.url)
最佳答案
我认为这不可能通过 JSONDecoder
自定义或在序列化层中实现,正如您在帖子中提到的那样。您能实现的最好结果就是这样做:
struct Response: Decodable {
let urlString: String
var url: URL {
URL(string: urlString.replacingOccurrences(of: " ", with: "%20"))!
}
enum CodingKeys: String, CodingKey {
case urlString = "url"
}
}
注意:如果您没有自定义实现,则不需要 init(decoder:)
。如果属性名称与字符串键相同,也不需要 CodingKeys
枚举(在您的情况下 url
键是多余的)。
关于swift - 从可解码模型中解码带有空格的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62221711/