使用Gloss框架可解码,可编码,光面一致性问题

时间:2017-09-05 15:25:09

标签: 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
            ])
    }

}

但我得到了:

  

键入&#39;用户&#39;不符合协议&#39; Encodable&#39;

  

&#39; JSON&#39;不能转换为&#39; JSON&#39; ...

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您的代码唯一的问题是引用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)。