4

我有以下型号:

struct Shop: Decodable {
    let id: Int
    let name: String
    let products: [Product]

    private enum CodingKeys: String, CodingKey {
        case id
        case name
        case products
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: .id)
        self.name = try container.decode(String.self, forKey: .name)
        self.products = try container.decode([Product].self, forKey: .products)
    }
}

struct Product: Decodable {
    let id: Int
    let title: String
    let productImageURL: String
    private(set) var productDetails: ProductDetails

    private enum CodingKeys: String, CodingKey {
        case id
        case title
        case productImageList
        case productImageDetails
        case productDetails
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: .id)
        self.title = try container.decode(String.self, forKey: .title)
        self.productDetails = try container.decode(ProductDetails.self, forKey: .productDetails)

        guard let serializationType = decoder.userInfo[.serializationType] as? SerializationGenericType else {
            throw NetworkError.modelParsingError(message: "Product model missing serialization type")
        }

        switch serializationType {
        case .list:
            self.productImageURL = try container.decode(String.self, forKey: .productImageList)
        case .details:
            self.productImageURL = try container.decode(String.self, forKey: .productImageList)
            self.productDetails = try container.decode(ProductDetails.self, forKey: .productDetails)
        }
    }
}

当然,模型要复杂得多,但这足以解释我的问题:)

另外,请不要介意编码键和图像 URL,这只是为了表明对于不同的序列化类型,它的初始化方式不同。

获取产品详细信息时,我有:

let decoder = JSONDecoder()
decoder.userInfo[.serializationType] = SerializationGenericType.details
let product = try decoder.decode(Product.self, from: data)

Shop但是当我在初始化用户信息时尝试传递序列化类型时,JsonDecoder如下所示:

let decoder = JSONDecoder()
decoder.userInfo[.serializationType] = SerializationGenericType.list
let shop = try decoder.decode(Shop.self, from: data)

Product初始化程序中,用户信息为空。

我的问题是如何将序列化类型从 传播Shop到 ,Product以便我可以使用正确的序列化类型正确解码它?

4

0 回答 0