这是我正在使用的代码,
struct CreatePostResponseModel : Codable{
var transcodeId:String?
var id:String = ""
enum TopLevelCodingKeys: String, CodingKey {
case _transcode = "_transcode"
case _transcoder = "_transcoder"
}
enum CodingKeys:String, CodingKey{
case id = "_id"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcode) {
self.transcodeId = transcodeId
}else if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcoder) {
self.transcodeId = transcodeId
}
}
}
在这里,
transcodeId
由_transcode
或_transcoder
决定。但我希望
id
和其余键(此处未包括)可以自动解码。我该怎么做 ?
最佳答案
一旦以init(from:)
类型实现Codable
,就需要手动解析所有键。
struct CreatePostResponseModel: Decodable {
var transcodeId: String?
var id: String
enum CodingKeys:String, CodingKey{
case id, transcode, transcoder
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcode) {
self.transcodeId = transcodeId
} else if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcoder) {
self.transcodeId = transcodeId
}
}
}
在上面的代码中,
Codable
。使用Decodable
就足够了。 enums
使用多个CodingKey
。您可以使用一个enum CodingKeys
。 rawValue
中显式指定该case
的enum CodingKeys
。因此,"_transcode"
中不需要"_transcoder"
和rawValues
TopLevelCodingKeys
。 除此之外,您还可以将
keyDecodingStrategy
用作.convertFromSnakeCase
来处理下划线表示法( snake case表示法),即do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase //here.....
let model = try decoder.decode(CreatePostResponseModel.self, from: data)
print(model)
} catch {
print(error)
}
因此,您无需显式处理所有蛇形键。它将由
JSONDecoder
自行处理。
关于ios - 如何手动对选定的按键进行解码,以及如何利用快速解码功能自动解码呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215567/