尝试解码可以是 String 或 Int 的 JSON 值

问题描述 投票:0回答:1

尝试解码可以是字符串或整数的 JSON 值“版本”并找到此解决方案如何解码可以是字符串或整数的 JSON 值这给了我一个错误“候选人要求‘SavedFavBooksFromISBN.Edition’符合到“PersistentModel”(要求指定为“Value”:“PersistentModel”)”

任何人都可以协助如何解码这个可以是 String 或 Int 的值吗?

代码如下

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]
}
json swift decode
1个回答
0
投票

要使模型可解码,您需要让所有结构和枚举符合

Codable
,所以用这个:

 enum Edition: Codable {
     case int(Int)
     case string(String)
 }
© www.soinside.com 2019 - 2024. All rights reserved.