我只需要为以下类手动自定义一个编码键
@objcMembers class Article :Object, Decodable{
dynamic var id: Int = 0
dynamic var title: String = ""
dynamic var image: String = ""
dynamic var author : String = ""
dynamic var datePublished: Date?
dynamic var body: String?
dynamic var publisher: String?
dynamic var url: String?
}
所以我必须添加以下枚举
private enum CodingKeys: String, CodingKey {
case id
case title = "name"
case image
case author
case datePublished
case body
case publisher
case url
}
因此,我已将所有类成员添加到 CodingKeys 枚举中,以便将标题覆盖为“name”。
有什么方法可以让我只添加我想要自定义的情况到枚举吗???
最佳答案
对于 Xcode 9.3 或更高版本
您可以通过结合三件事来实现这一目标:
- 一个
GenericCodingKeys
结构,允许我们使用任意字符串值创建编码 key 。 - 将 JSON 键映射到资源名称的函数(
name
→title
) - 设置
keyDecodingStrategy = .custom(...)
在JSONDecoder
对象
试试这个:
import Foundation
// A struct that allows us to construct arbitrary coding keys
// You can think of it like a wrapper around a string value
struct GenericCodingKeys: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) { self.stringValue = stringValue }
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
}
@objcMembers class Article: NSObject, Decodable {
dynamic var id: Int = 0
dynamic var title: String = ""
dynamic var image: String = ""
dynamic var author : String = ""
dynamic var datePublished: Date?
dynamic var body: String?
dynamic var publisher: String?
dynamic var url: String?
static func codingKeyMapper(path: [CodingKey]) -> CodingKey {
// `name` is the key in JSON. `title` is your property name
// Here, we map `name` --> `title`
if path.count == 1 && path[0].stringValue == "name" {
return GenericCodingKeys(stringValue: "title")!
} else {
return path.last!
}
}
}
let json = """
{
"id": 1,
"name": "A title",
"image": "An image",
"author": "Any author",
}
""".data(using: .utf8)!
// Configure the decoder object to use a custom key decoding strategy
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom(Article.codingKeyMapper)
let article = try decoder.decode(Article.self, from: json)
print(article.title)
关于ios - Swift Codable 无法仅自定义所需的按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52926987/