提问者:小点点

理解Realm,Moya和ObjectMapper


所以我试图弄清楚如何使用Realm,Moya和ObjectMapper。

我使用Moya向我的API发出请求。我使用Realm将返回的数据保存在本地数据库中。并且我使用ObjectMapper将JSON对象映射到校正领域变量。

然而,现在我遇到了一个问题,我不确定如何解码JSON响应以便将其通过映射器。

下面是我的莫亚密码:

provider.request(.signIn(email: email, password: password)) { result in
    switch result {
    case let .success(response):
        do {
            // Get the response data
            let data = try JSONDecoder().decode(MyResponse.self, from: response.data)

            // Get the response status code
            let statusCode = response.statusCode

            // Check the status code
            if (statusCode == 200) {
                // Do stuff
            }
        } catch {
            print(error)
        }
    case let .failure(error):
        print(error)
        break
    }
}

错误发生在这一行:

In argument type 'MyResponse.Type', 'MyResponse' does not conform to expected type 'Decodable'

类如下所示:

class MyResponse: Object, Mappable {
    @objc dynamic var success = false
    @objc dynamic var data: MyResponseData? = nil

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

    func mapping(map: Map) {

    }
}

我明白为什么我会犯这个错误,但我不知道正确的解决方法。我是不是在上面某个框架的文档中遗漏了什么?我这样做完全错了吗?我应该如何修复我的代码行?

我尝试了@kamran's的解决方案,但我得到了一个错误:

null

在线上:

let myResponse = MyResponse(JSON: json)

共1个答案

匿名用户

出现该错误是因为您正在使用Swift JSONDecoder进行解码,它要求您实现Codable,Codable包装了Encodable和Decodable(JSON<-&>YourObject)。

如果你正在使用Swift4,你可以使用Codable而不是依赖于第三方库。

我的回应将变成:

class MyResponse: Codable {
    let success: Bool
    let data: MyResponseData? 
}

MyResponseData也应该实现可编码。

在此之后,您应该能够执行以下操作:

do {
    let data = try JSONDecoder().decode(MyResponse.self, from: response.data)
} catch let error { 
    // handle error
}