NSObject Decodable相同的值

时间:2019-01-08 04:11:59

标签: swift

JSON:

{
   "words": "1"
}

有时是键wordsword

解析此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)
    }
}

1 个答案:

答案 0 :(得分:0)

您应在decodeIfPresent期间使用decodingif 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)
}