2017-03-08 79 views
0

我有一個自定義的ObjectMapper類。 我想基於數據將元素映射到不同的對象類型。 我已經實現瞭如下的邏輯。但它不給我的價值,只有空。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" }] }

+0

你能分享一個JSON響應嗎? –

+0

@anilkukdeja添加樣本json –

+0

請查看我的答案。 –

回答

0

我想你應該保存整個數組對象。

這裏讓我們轉到您的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() 

} 

之後,你可以迭代你的數組對象並比較類型。讓我知道你是否需要任何進一步的幫助。

+0

我也爲此準備了seprate演示。讓我知道你是否需要演示。 –