swift - 从可解码模型中解码带有空格的 url

标签 swift decodable

我有以下结构,响应解析失败,因为 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/

相关文章:

ios - 使用 Decodable + Realm Swift 解码自定义 JSON

swift - 类型 'DBTweet' 不符合协议(protocol) 'Decodable'

ios - 解码为 NSManagedObject 对象后需要获取请求

ios - Apple ARKit (Augmented Reality Kit) 给出断言失败的错误信息

swift - 如何在访问前一个 Controller 期间处理 nil(同时展开可选值)

swift - 往返 Swift 数字类型到/从数据

ios - 面朝上或面朝下风景方向

json - 在 Swift 中解码不同类型的 JSON 数组

ios - 可在 Swift 中使用子类解码

ios - 以编程方式将 UIImage 添加到 ImageView 中,以非编程方式 SWIFT