【发布时间】:2019-12-11 10:09:51
【问题描述】:
假设 JSON 看起来像这样:
{
"users": [
{
"id": 6,
"email": "123@gmail.com"
},
{
"id": 2,
"email": "345@gmail.com"
}
],
"meta": {
"current_page": 1,
"next_page": 2,
"prev_page": null,
"total_pages": 3,
"total_count": 12
}
}
有时它可能看起来像这样
{
"messages": [
{
"id": 6,
"text": "hello"
},
{
"id": 2,
"text": "hi"
}
],
"meta": {
"current_page": 1,
"next_page": 2,
"prev_page": null,
"total_pages": 3,
"total_count": 12
}
}
如您所见,codingkey 会根据 JSON 中的对象而变化。 如何将此 JSON 解析为我可以阅读且动态的内容,例如:
struct GenericListModel<ListObject: Codable>: Codable {
let list: [ListObject]
let page: PaginationModel
}
我将在哪里分别创建 ListObject,例如:UserModel。
然后我将创建模型:
GenericListModel<UserModel>(list: UserModel(id: 6, email: "123@gmail.com"), page: PaginationModel())
【问题讨论】:
标签: json swift generics codable