【问题标题】:Object Mapper - parsing array of [AnyObject]对象映射器 - 解析 [AnyObject] 的数组
【发布时间】:2016-08-17 09:23:23
【问题描述】:

我有来自 API 的多类型对象的响应 JSON。

它内部有type 属性。现在我正在尝试基于type 属性应用某种自动映射,但我无法以任何方式使其工作。

private let modelClassMap = [
    "first_type": First.self
]

func createModelWithDictionary(json: [String: AnyObject]) -> [AnyObject] {
    var items: [AnyObject]
    if let items = json["items"] as? [[String: AnyObject]] {
        for item in items {
            if let typeString = item["type"] as? String {
                var Type = self.modelClassMap[typeString]
                items.append(Mapper<Type>().map(item))
            }
        }
    }
    return items
}

我得到的错误是Type is not a type

【问题讨论】:

  • 抱歉,您的项目中有这个模型?如果不存在,则无法映射类型。如果您想映射 Json 中描述的任何新类型,那么方法太长了。
  • @Patonz - 是的。它们是现有的可映射对象:)

标签: ios json swift parsing objectmapper


【解决方案1】:

您尝试做的事情实际上是不可能的,因为模板的关联类型不是运行时的。编译器需要在编译时知道类型。

我们可以做一些不同的事情,使用枚举:

enum ModelClassMap: String {
    case FirstType = "first_type"

    func map(item: [String: AnyObject]) -> AnyObject? {
        switch self {
        case FirstType:
            return Mapper<First>().map(item)
        }
    }
}

在你的 for 循环中,你可以尝试将字符串转换为枚举:

func createModelWithDictionary(json: [String: AnyObject]) -> [AnyObject] {
    var mappedItems: [AnyObject] = []
    if let items = json["items"] as? [[String: AnyObject]] {
        items.forEach() {
            if let typeString = $0["type"] as? String,
                let mappedType = ModelClassMap(rawValue: typeString),
                let mappedObject = mappedType.map($0) {
                // mappedObject represents an instance of required object, represented by "type"
                mappedItems.append(mappedObject)
            }
        }
    }
    return mappedItems
}

【讨论】:

  • 这就是我的假设。谢谢你的答案。那么我坚持使用简单开关的任一地图。
猜你喜欢
  • 1970-01-01
  • 2017-06-03
  • 2019-05-15
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多