我有一个JSON文件和一个相关的类。我通过调用init?(data:Data)初始化器来解码它。我从端点获取此JSON。我想用SHA-256加密URL文本。我的问题是我想在解码数据时解密这个URL字符串。所以在解码URL时,需要调用一个函数。有可能这样做吗?
PS:我知道我可以写加密文本并在我使用的地方解密,但我想将此作为最后一个选项。
struct TableCellData: Codable {
let type: Int
let cellText: String
let cellImage: String?
let url: URL?
let detailText: String?
let tableID: Int?
enum CodingKeys: String, CodingKey {
case type = "type"
case cellText = "cell_text"
case cellImage = "cell_image"
case url = "url"
case detailText = "detail_text"
case tableID = "table_id"
}
}
extension TableCellData {
init?(data: Data) {
guard let me = try? JSONDecoder().decode(TableCellData.self, from: data) else { return nil }
self = me
}
init?(_ json: String, using encoding: String.Encoding = .utf8) {
guard let data = json.data(using: encoding) else { return nil }
self.init(data: data)
}
init?(fromURL url: String) {
guard let url = URL(string: url) else { return nil }
guard let data = try? Data(contentsOf: url) else { return nil }
self.init(data: data)
}
var jsonData: Data? {
return try? JSONEncoder().encode(self)
}
var json: String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
}
答案 0 :(得分:1)
如果我理解正确,你有一个字段URL,你将在服务器端SHA256加密。 然后,您将在json中加密它,并且您希望在类实例中对其进行解密。
如果是这样,只需查看文档:{{3}}并搜索标题:手动编码和解码
第一个代码块是结构,第二个是自定义解析器,你可以在其中加密你的字段。
修改:
我很遗憾没有时间为你编写代码,但也许这个更深入的关于Encodable和编码键的教程将帮助你(寻找标题"手动编码和解码") :encoding and decoding custom types
它的要点非常简单:您可以在可解码扩展中提供自己的解码逻辑。在这里,他们将尺寸变量分组为宽度和高度:
struct Photo
{
var title: String
var size: Size
enum CodingKeys: String, CodingKey
{
case title = "name"
case width
case height
}
}
extension Photo: Encodable
{
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(title, forKey: .title)
try container.encode(size.width, forKey: .width)
try container.encode(size.height, forKey: .height)
}
}
extension Photo: Decodable
{
init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decode(String.self, forKey: .title)
let width = try values.decode(Double.self, forKey: .width)
let height = try values.decode(Double.self, forKey: .height)
size = Size(width: width, height: height)
}
}