JSON:
{
"words": "1"
}
有时是键words
或word
解析此JSON时失败,并显示以下错误
错误:
keyNotFound(CodingKeys(stringValue:“ paragraph”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription:“没有与键CodingKeys(stringValue:\” paragraph \“,intValue:nil相关联的值) )(\“ paragraph \”)。“,underlyingError:nil))。段落是
@objcMembers class EmphasisModel: NSObject ,Codable{
var words:String?
}
enum CodingKeys: String, CodingKey {
case word,words
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.words = try container.decode(String?.self, forKey: .words)
if self.words != nil {
self.words = try container.decode(String?.self, forKey: .word)
}
}
答案 0 :(得分:0)
您应在decodeIfPresent
期间使用decoding
。 if statement
是错误的。它应该检查是否等于nil而不是non-nil。
class EmphasisModel: Decodable {
var words: String?
enum CodingKeys: String, CodingKey {
case word, words
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.words = try container.decodeIfPresent(String.self, forKey: .words)
if self.words == nil {
self.words = try container.decodeIfPresent(String.self, forKey: .word)
}
}
}
用法
let data = """
{ "words": "1" }
""".data(using: .utf8)!
do {
let ad = try JSONDecoder().decode(EmphasisModel.self, from: data)
print(ad?.words)
} catch {
print(error)
}