I'm using the Swift 4 Codable
protocol with JSON data. My data is formatted such that there is a single key at the root level with an object value containing the properties I need, such as:
{
"user": {
"id": 1,
"username": "jdoe"
}
}
我有一个User
struct ,可以解码user
键:
struct User: Codable {
let id: Int
let username: String
}
因为id
和username
是user
的属性,而不是在根级别,所以我需要创建一个如下的包装器类型:
struct UserWrapper: Codable {
let user: User
}
然后我可以通过UserWrapper
解码JSON,User
也被解码.这似乎有很多冗余代码,因为我的每个类型都需要一个额外的包装器.有没有一种方法可以避免这种包装器模式,或者有一种更正确/更优雅的方法来处理这种情况?