尝试解码可以是字符串或整数的 JSON 值“edition”,并找到此解决方案如何解码可以是字符串或整数的 JSON 值,这给了我一个错误“候选人要求'SavedFavBooksFromISBN.Edition'符合'PersistentModel'(要求指定为'Value':'PersistentModel')”
有人能帮忙解码这个可以是字符串或整数的值吗?
代码如下
import Foundation
import SwiftData
struct Response: Decodable {
let bookObjects: [SavedFavBooksFromISBN]
}
@Model class SavedFavBooksFromISBN: Decodable, Identifiable, Hashable {
private(set) var id: String
private(set) var title: String
private(set) var language: String?
private(set) var edition: Edition
init(id: String, edition: Edition, language: String?, title: String) {
self.id = id
self.title = title
self.language = language
self.edition = edition
}
enum Edition: Decodable {
case int(Int)
case string(String)
}
enum CodingKeys: String, CodingKey {
case id = "isbn13"
case title
case language
case edition
}
required init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title).trunc(length: 1500)
id = try container.decode(String.self, forKey: .id)
language = try container.decodeIfPresent(String.self, forKey: .language)
if let value = try? container.decode(Int.self, forKey: .edition) {
self.edition = .int(value)
} else if let value = try? container.decode(String.self, forKey: .edition) {
self.edition = .string(value)
} else {
let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unable to decode value for `edition`")
throw DecodingError.typeMismatch(Edition.self, context)
}
} //end init
}
struct BookDataStore: Decodable {
var books: [SavedFavBooksFromISBN]
}
为了使模型可解码,您需要使所有结构体和枚举属性符合
Codable
,因此请使用以下命令修复您的错误: