1.前言: 今天遇到一个后台网络key值相同,而值类型不同的问题.如图所示
![](media/15338948412344/15338949888327.jpg)
2.解决方法
使用StaticMappable Protocol
class Message: StaticMappable {
var message_type = "" // "Text",
var user_id = "" // "a1ace6d8-0301-4ff7-8c4c-d29b0727fc48",
var id = "" // "91fa4a75-da17-4786-9cce-2f753bdf2853",
var origin = "" // "Student",
var time = "" // "20180809T162722+0800"
func mapping(map: Map) {
message_type <- map["message_type"]
user_id <- map["user_id"]
id <- map["id"]
origin <- map["origin"]
time <- map["time"]
}
static func objectForMapping(map: Map) -> BaseMappable? {
if let type: String = map["message_type"].value() {
switch type {
case "Text":
return TextMessage()
case "Json":
return VoiceMessage()
default:
return Message()
}
}
return nil
}}
class TextMessage: Message {
var message = ""
override func mapping(map: Map) {
super.mapping(map: map)
message <- map["message"]
}}
class VoiceMessage: Message {
var message: ResourceInfo?
override func mapping(map: Map) {
super.mapping(map: map)
message <- map["message"]
}}
extension VoiceMessage {
class ResourceInfo: Mappable {
var file_id = "" // "c067371c-e15f-43bf-a847-8b5b275aea1c",
var file_name = "" // "1533803276392temp.arm",
var url = "" // "/homeschool_chat/file/c067371c-e15f-43bf-a847-8b5b275aea1c",
var file_size = 0 // 2757,
var content_type = "" // "voice/arm",
var object_name = "" // "c067371c-e15f-43bf-a847-8b5b275aea1c",
var bucket_name = "" // "chat"
required init?(map: Map) {
}
func mapping(map: Map) {
file_id <- map["file_id"]
file_name <- map["file_name"]
url <- map["url"]
file_size <- map["file_size"]
content_type <- map["content_type"]
object_name <- map["object_name"]
bucket_name <- map["bucket_name"]
}}
}
网友评论