我正尝试解码来自第三方API的JSON响应,其中包含了被base64编码的嵌套/子JSON数据。
虚构的JSON示例
{
"id": 1234,
"attributes": "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9",
}
PS "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9"
是以 base64 编码的 { 'name': 'some-value' }
。
目前我有一些能够解码它的代码,但不幸的是我必须在 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
的情况下完成解码?
附注:我无法控制响应格式,它不能被更改。
JSONDecoder
有什么缺点?(我认为你无法避免它) - New DevconvertFromSnakeCase
或dateDecodingStrategy
,因为数据格式可能根本不是 JSON,有人可能正在尝试以 XML 格式解码相同的模型。 - Oliver Pearmain