【发布时间】:2021-01-14 12:22:43
【问题描述】:
我正在尝试解码来自第三方 API 的 JSON 响应,其中包含经过 base64 编码的嵌套/子 JSON。
人为的 JSON 示例
{
"id": 1234,
"attributes": "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9",
}
PS "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9" 是 { 'name': 'some-value' } base64 编码的。
我目前有一些能够解码的代码,但不幸的是,我必须在 init 内重新实例化一个额外的 JSONDecoder() 才能这样做,这并不酷......
人为的示例代码
struct Attributes: Decodable {
let name: String
}
struct Model: Decodable {
let id: Int64
let attributes: Attributes
private enum CodingKeys: String, CodingKey {
case id
case attributes
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int64.self, forKey: .id)
let encodedAttributesString = try container.decode(String.self, forKey: .attributes)
guard let attributesData = Data(base64Encoded: encodedAttributesString) else {
fatalError()
}
// HERE IS WHERE I NEED HELP
self.attributes = try JSONDecoder().decode(Attributes.self, from: attributesData)
}
}
有没有办法在不实例化额外的JSONDecoder的情况下实现解码?
PS:我无法控制响应格式,也无法更改。
【问题讨论】:
-
出于好奇,使用额外的
JSONDecoder有什么缺点? (我认为你无法避免) -
我能想到的一些原因...因为新的解码器可能有与原始解码器不同的选项(例如
convertFromSnakeCase或dateDecodingStrategy),因为数据格式可能根本不是 JSON ,有人可能会尝试以 XML 格式解码相同的模型。 -
您可以在“主”解码器的
userInfo中放置一个自定义解码器(可以是具有相同选项的解码器)。 -
@Larme 所说的,......而且,它可能是与父对象的解码器不同的数据格式(例如 JSON 中的 XML),这是我想为什么它的原因应该是一个额外的(或不同的)解码器