如何使用 Swift JSON Decoder 直接解码字典中包含的数组?

发布于 2025-01-15 03:12:33 字数 734 浏览 5 评论 0原文

假设我们有一个像这样的 json 对象:

{
  "count": 2,
  "users": [
    {
      "name": "tom",
      "id": 123
    },
    {
      "name": "cat",
      "id": 456
    }
  ]
}

User 结构如下:

struct User: Decodable {
    let name: String
    let id: Int
}

显然,您可以创建另一个名为 Root 的结构来使用 JSONDecoder< 解码 json 对象/code>:

struct Root: Decodable {
    let count: Int,
    let users: [User]
}

let root = try JSONDecoder().decode(Root.self, from: json)
let users = root.users

但实际上 Root 对我来说没什么用,嵌套的 users 只是我关心的。那么,如何仅将 users 部分解码为 [User] 而不使用不必要的 Root 结构呢?

Suppose we have a json object like this:

{
  "count": 2,
  "users": [
    {
      "name": "tom",
      "id": 123
    },
    {
      "name": "cat",
      "id": 456
    }
  ]
}

and the User struct would be like:

struct User: Decodable {
    let name: String
    let id: Int
}

Obviously you can create another struct named Root to decode the json object using JSONDecoder:

struct Root: Decodable {
    let count: Int,
    let users: [User]
}

let root = try JSONDecoder().decode(Root.self, from: json)
let users = root.users

but actually Root is useless for me, the nested users is only what I concerned. So how can I decode only the users part into [User] without the needless Root struct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文