gpt4 book ai didi

ios - ObjectMapper 条件映射整个元素

转载 作者:行者123 更新时间:2023-11-30 12:37:39 26 4
gpt4 key购买 nike

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

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”:[
{
“类型”:“正常”,
“状态”:“无”,
“邀请”:假,
“评论”:“你好”,
“时间”:“00:12”
},
{
“类型”:“正常”,
“状态”:“无”,
“邀请”:真实,
"comment": "你好吗?",
“时间”:“04:15”
},
{
“类型”:“ friend ”,
"display_text": "你的 friend 在这里。",
“计数”:23
},
{
“类型”:“正常”,
“状态”:“已验证”,
“邀请”:真实,
“评论”:“太棒了”,
“时间”:“09:32”
}]
}

最佳答案

I think you should store entire array object.

在这里,让我们转到您正在获取响应的 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()

}

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

关于ios - ObjectMapper 条件映射整个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com