ios - 使用 Gloss 框架的可解码、可编码、光泽一致性问题

标签 ios json swift serialization swift3

我尝试使用 Gloss为了序列化和反序列化来自 JSON/Swift 对象的传入和传出网络数据:

struct User: Decodable, Glossy {

    let id: Int?
    let username: String?

    init?(json: JSON) {
        self.id = "id" <~~ json
        self.username = "username" <~~ json
    }

    func toJSON() -> JSON? {
        return jsonify([
            "id" ~~> self.ownerId,
            "username" ~~> self.username
            ])
    }

}

但是我得到了:

Type 'User' does not conform to protocol 'Encodable'

'JSON' is not convertible to 'JSON'...

有人可以帮我解决这个问题吗?

最佳答案

您的代码唯一的问题是引用了 ownerId 而不是 id。如果您使用 Glossy,则无需指定 Gloss.Decodable,因为它是 Gloss.DecodableGloss.Encodable 的组合:

import Gloss

// If you use Glossy, there's no need to use Gloss.Decodable since it's a composition of both Decodable, Encodable
struct User: Glossy {
    let id: Int?
    let username: String?

    // Gloss.Decodable
    init?(json: JSON) {
        self.id = "id" <~~ json
        self.username = "username" <~~ json
    }

    // Gloss.Encodable
    func toJSON() -> JSON? {
        return jsonify([
            "id" ~~> self.id,
            "username" ~~> self.username
        ])
    }

}

使用 Swift 3.1、3.2、4 进行测试(考虑迁移到 Swift 4 Codable)。

关于ios - 使用 Gloss 框架的可解码、可编码、光泽一致性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058550/

相关文章:

ios - 在动态创建的 uibuttons 上未检测到单击

swift - 毫秒计时器?

ios - 使用 cocoa pod 后没有这样的模块 ssziparchive

php - 无法对类型对象进行非规范化,找不到支持的规范化器。 Symfony 2.8

javascript - 快速发送 json 但客户端接收未定义

ios - Firebase 通知默认图像 iOS

ios - 如何获取CLLocationManager当前坐标

ios - 使用 iOS/Swift 进行身份验证

objective-c - 我应该在 Objective C 类中的什么位置设置默认变量值

java - PendingTransactionsTest 类型的给定方法未定义