首页 > 解决方案 > 如何从可编码结构中检索数据,该结构可能将空数组作为其值之一,而不是字典?

问题描述

这是我的结构

    struct AFilters: Codable {
            let colors, sizes, materials,lining, price: MaterialsClass?
            //let lining, price: Lining?

       struct MaterialsClass: Codable {
                let id: [Int]
                let name: String
                let items: ItemAny
        }

        enum ItemAny: Codable {
                case anythingArray([JSONAny])
                case itemMap([String: Item])

                init(from decoder: Decoder) throws {
                    let container = try decoder.singleValueContainer()
                    if let x = try? container.decode([JSONAny].self) {
                        self = .anythingArray(x)
                        return
                    }
                    if let x = try? container.decode([String: Item].self) {
                        self = .itemMap(x)
                        return
                    }
                    throw DecodingError.typeMismatch(Extenders.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Extenders"))
                }

                func encode(to encoder: Encoder) throws {
                    var container = encoder.singleValueContainer()
                    switch self {
                    case .anythingArray(let x):
                        try container.encode(x)
                    case .itemMap(let x):
                        try container.encode(x)
                    }
                }
            }

        struct Item: Codable {
                let name: String
                let value: String?
                let active: Bool
            }
    }
}

这些是可能来自 API 的响应类型

"lining": {
   "id": [6],
    "name": "Подкладка",
    "items": []
 }

"materials": {
     "id": [4],
     "name": "Материал",
     "items": {
        "143": {
           "name": "Полиэстер",
            "value": null,
            "active": false
        }
      }
 }

我能够将这种类型的响应解析到模型中,然后将其保存到变量中

var filter = Afilters
filter = list.apiData.aFilters

现在,即使响应包含 dict,我也无法获取项目数据

如何从过滤器中获取值?

标签: jsonswiftparsingcodable

解决方案


推荐阅读