您可以实现自己的decode init方法,从decode container中获取每个类属性,在这一节中,使您处理“rating”是int还是string的逻辑,最后对所有必需的类属性进行签名。
以下是我制作的一个简单演示:
class Demo: Decodable {
var test = 0
var rating: String?
enum CodingKeys: String, CodingKey {
case test
case rating
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let test = try container.decode(Int.self, forKey: .test)
let ratingString = try? container.decode(String.self, forKey: .rating)
let ratingInt = try? container.decode(Int.self, forKey: .rating)
self.rating = ratingString ?? (ratingInt == 0 ? "rating is nil or 0" : "rating is integer but not 0")
self.test = test
}
}
let jsonDecoder = JSONDecoder()
let result = try! jsonDecoder.decode(Demo.self, from: YOUR-JSON-DATA)
-
如果rating api的值是普通字符串,您将得到它。
-
如果等级API的值为0,则等级将等于“等级为零或0”
-
如果rating api的值是其他整数,则rating将是“rating is integer but not 0”
你可以修改解码的“评分”结果,这应该很容易。
希望这能给你点帮助。:)
更多信息:
Apple's encoding and decoding doc