使用 ObjectMapper 映射 JSON 对象的通用函数

Posted

技术标签:

【中文标题】使用 ObjectMapper 映射 JSON 对象的通用函数【英文标题】:Generic function to map JSON objects with ObjectMapper 【发布时间】:2016-10-01 08:13:01 【问题描述】:

我有一个通用函数:

   func toObjectMapper<T: Mappable>(mapper: T, success: (result: Mappable) -> Void, failure: (error: NSError) -> Void)
        let alomofireApiRequest = AlamofireApiRequest(apiRequest: self)
        Alamofire.request(alomofireApiRequest)
            .responseObject  (response: Response<T, NSError>) in
                guard let value = response.result.value else 
                    failure(error: response.result.error!)
                    return
                
                success(result: value)
        

    

我想这样称呼它:

public func login(login: String, password: String) -> UserResponse 
        let params = ["email":login, "password":password]

        let request = ApiRequest(method: .POST, path: "login", parameters: params)

        request.toObjectMapper(UserResponse.self, success:  result in
                print(result)

            , failure:  error in
                print(error.description)
        )
    

但我总是得到这个错误:

 Cannot invoke 'toObjectMapper' with an argument list of type '(UserResponse.Type, success: (result: Mappable) -> Void, failure: (error: NSError) -> Void)'

这是我的用户回复:

import Foundation
import ObjectMapper
import RealmSwift

public class  UserResponse: Object, Mappable 
    dynamic var id = 0
    dynamic var name = ""
    dynamic var address = ""
    dynamic var zipcode = ""
    dynamic var city = ""
    dynamic var country = ""
    dynamic var vat = ""
    dynamic var email = ""
    dynamic var created_at = NSDate()
    dynamic var updated_at = NSDate()

    override public static func primaryKey() -> String? 
        return "id"
    

    //Impl. of Mappable protocol
    required convenience public init?(_ map: Map) 
        self.init()
    

    public func mapping(map: Map) 
        id    <- map["id"]
        name <- map["name"]
        address <- map["address"]
        zipcode <- map["zipcode"]
        city <- map["city"]
        country <- map["country"]
        vat <- map["vat"]
        email <- map["email"]
        created_at <- map["created_at"]
        updated_at <- map["updated_at"]


    

有什么帮助吗?

【问题讨论】:

【参考方案1】:

我认为问题在于您试图将 UserResponse 用作实例化对象,但使用 UserResponse.self 只是类类型。

一种解决方案是让 UserResonse 成为单例(或者只是在将实例作为参数传递给 'toObjectMapper' 之前实例化它)

我不知道这段代码是否特别有效,但大致如下:-

public class  UserResponse: Object, Mappable 
dynamic var id = 0
dynamic var name = ""
dynamic var address = ""
dynamic var zipcode = ""
dynamic var city = ""
dynamic var country = ""
dynamic var vat = ""
dynamic var email = ""
dynamic var created_at = NSDate()
dynamic var updated_at = NSDate()

static let shared = UserResponse() //singleton instantiation

override public static func primaryKey() -> String? 
    return "id"


//Impl. of Mappable protocol
required convenience public init?(_ map: Map) 
    self.init()


public func mapping(map: Map) 
    id    <- map["id"]
    name <- map["name"]
    address <- map["address"]
    zipcode <- map["zipcode"]
    city <- map["city"]
    country <- map["country"]
    vat <- map["vat"]
    email <- map["email"]
    created_at <- map["created_at"]
    updated_at <- map["updated_at"]




然后在你的函数调用中

public func login(login: String, password: String) -> UserResponse 
    let params = ["email":login, "password":password]

    let request = ApiRequest(method: .POST, path: "login", parameters: params)

    request.toObjectMapper(UserResponse.shared, success:  result in
            print(result)

        , failure:  error in
            print(error.description)
    )

【讨论】:

我做了一个快速测试,它消除了警告。所以你需要实例化一个 UserResponse 的实例。以上只是我将如何做的一个粗略示例。

以上是关于使用 ObjectMapper 映射 JSON 对象的通用函数的主要内容,如果未能解决你的问题,请参考以下文章

使用 ObjectMapper 映射 JSON 对象的通用函数

AlamofireObjectMapper / ObjectMapper 是不是支持结构类型映射

将 JSON 映射到我的模型数组 - ObjectMapper

Swift - 嵌套对象的映射 (Objectmapper)

ObjectMapper的使用

jackson中objectMapper的使用