我尝试使用 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.Decodable
、Gloss.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/