【问题标题】:ObjectMapper conditional mapping whole elementObjectMapper 条件映射整个元素
【发布时间】:2017-03-08 12:29:02
【问题描述】:

我有一个自定义的 ObjectMapper 类。 我想根据数据将元素映射到不同的对象类型。 我已经实现了如下的逻辑。但它没有给我价值,只有空值。

class FeedObject : Object, Mappable {

    dynamic var post : HomeDataModel?
    dynamic var friends : Friends?

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        var Mtype = ""
        Mtype <- map["type"]
        print("TYPEEEEEE", Mtype)

        if Mtype == "FRIENDS" {
            friends <- map
        }
        else {
            post <- map
        }
    }
}

如何实现这种映射?

示例 Json -

{ "feed_objects": [ { "type": "NORMAL", "status": "none", "invited": false, "comment": "hello", "time": "00:12" }, { "type": "NORMAL", "status": "none", "invited": true, "comment": "How are you?", "time": "04:15" }, { "type": "FRIENDS", "display_text": "Your friends are here.", "count": 23 }, { "type": "NORMAL", "status": "verified", "invited": true, "comment": "great", "time": "09:32" }] }

【问题讨论】:

  • 你能分享一个 JSON 响应吗?
  • @anilkukdeja 添加了示例 json
  • 请查看我的回答。

标签: ios swift swift3 objectmapper


【解决方案1】:

我认为你应该存储整个数组对象。

这里让我们转到您获得响应的 Web 服务解析方法。

if let responseValue = response.result.value as? [String:AnyObject]{ 
    if let feedObject = Mapper<Feed>().mapArray(JSONArray:data){
             print(feedObject)
    }
}

定义你的 Feed 类是这样的。

import ObjectMapper

class Feed: Mappable, CustomStringConvertible {

    required init?(map: Map) {}

    func mapping(map: Map) {
        type <- map["type"]
        status <- map["status"]
        comment <- map["comment"]
        time <- map["time"]
        invited <- map["invited"]
    }

    var description: String {
        get {
            return Mapper().toJSONString(self, prettyPrint: false)!
        }
    }

     var type:String = String()
     var status:String = String()
     var comment:String = String()
     var time:String = String()
     var invited : Bool = Bool()

}

之后,您可以遍历数组对象并比较类型。如果您需要任何进一步的帮助,请告诉我。

【讨论】:

  • 我也为此准备了单独的演示。如果您需要演示,请告诉我。
【解决方案2】:

Anil 的答案不是正确/有效的方法,您将在一次映射迭代后重新处理数据集。 您需要为映射定义自己的转换。看看这个:How to map different type using ObjectMapper?

【讨论】:

    猜你喜欢
    • 2018-04-22
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2016-05-25
    • 2010-10-11
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多