为了序列化和反序列化来自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
])
}
}
但我得到了:
类型'User‘不符合协议'Encodable’
和
'JSON‘不能转换成’JSON‘.
有人能帮我解决这个问题吗?
发布于 2017-09-05 16:57:28
代码唯一的错误是引用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
])
}
}
使用SWIFT3.1,3.2,4进行测试(考虑迁移到Swift的4 Codable
)。
https://stackoverflow.com/questions/46058550
复制相似问题