首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift -使用decodable将嵌套对象转换为对象数组

Swift -使用decodable将嵌套对象转换为对象数组
EN

Stack Overflow用户
提问于 2020-08-11 18:25:15
回答 2查看 75关注 0票数 0

我有一个如下格式的JSON,其中有一个学生对象。学生对象中列出了多名学生

代码语言:javascript
复制
Student {
    student1: {
        id: "12",
        name: "jack",
    },
    student2: {
        id: "2323",
        name: "lewis"
    },
    student3: {
        id: "1212",
        name: "pint"
    }
}

我想把它转换成一个学生对象数组,如下所示。我如何使用decodable来做这件事?

代码语言:javascript
复制
struct student: Decodable {
    let name: String
    let id: String
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-11 18:58:08

也许这就是你想要的:

代码语言:javascript
复制
let json = """
{
  "student": {
      "student1": {
          "id": "12",
          "name": "jack",
      },
      "student2": {
          "id": "2323",
          "name": "lewis"
      },
      "student3": {
          "id": "1212",
          "name": "pint"
      }
  }
}
"""

struct Student: Decodable {
  let id: String
  let name: String
}

struct StudentContainer: Decodable {
  let students: [Student]

  private enum CodingKeys: String, CodingKey {
      case student
  }

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let studentsDict = try container.decode([String: Student].self, forKey: .student)
    self.students = studentsDict.map { $0.value }
  }
}

let result = try? JSONDecoder().decode(StudentContainer.self, from: json.data(using: .utf8)!)
票数 2
EN

Stack Overflow用户

发布于 2020-08-11 18:44:48

抱歉,我读错了一点,所以我再试一次。

要创建一个数组,您可以执行类似以下操作:

代码语言:javascript
复制
struct Students: Codable {
    let students: [Student]
}

struct Student: Codable {
    let name: String
    let id: String
} 

这足以将学生编码到一个数组中。只需使用Students传递JSON数据。

您必须稍微编辑您的JSON,如下所示:

代码语言:javascript
复制
{
    "students": [
        {
            id: "12",
            name: "jack",
        },
        {
            id: "2323",
            name: "lewis"
        },
        {
            id: "1212",
            name: "pint"
        }
    ]
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63356225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档