如何在Swift中将JSON解码并编码为通用结构

时间:2019-12-11 10:09:51

标签: json swift generics codable

说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())

1 个答案:

答案 0 :(得分:0)

您可能需要对其进行一些调整,但是您可以执行以下操作:

routeParam