Rad*_*dya 1 json ios swift decodable
所以我有一个用户JSON结构,如下所示:
- results: {
meta: {}
users: []
},
- status:
Run Code Online (Sandbox Code Playgroud)
我想得到用户所以User我实现的模型来获取JSON是这样的:
struct Response: Decodable {
let results: Result
let status: Int
}
struct Result: Decodable {
let meta: Meta
let users: [User]
}
struct Meta: Decodable {
let total_data: Int
let total_page: Int
}
struct User: Decodable {
let avatar_url: String
let created_at: String
let updated_at: String
let email: String
let id: Int
let name: String
let username: String
}
Run Code Online (Sandbox Code Playgroud)
它正在工作,但当我有另一个JSON结构相似时,就这样说吧
- results: {
meta: {}
rooms: []
},
- status:
Run Code Online (Sandbox Code Playgroud)
当我创建Room模型时,另一个struct Response在其上,它将导致错误,因为它是重复的声明.
是否有可能在Swift中重用struct?或者有没有方便的方法来做到这一点?
谢谢
你可以使用泛型.
struct Response<T: Decodable>: Decodable {
let results: Result<T>
let status: Int
}
struct Result<T: Decodable>: Decodable {
let meta: Meta
let objects: [T]
}
struct Meta: Decodable {
let total_data: Int
let total_page: Int
}
struct User: Decodable {
let avatar_url: String
let created_at: String
let updated_at: String
let email: String
let id: Int
let name: String
let username: String
}
let userResponse: Response<User>?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |