簡體   English   中英

Swift - 使用可解碼將嵌套對象轉換為對象數組

[英]Swift - Convert nested objects into an array of objects using decodable

我有一個以下格式的 JSON,其中有一個學生 object。 學生 object 列出了多個學生

Student {
    student1: {
        id: "12",
        name: "jack",
    },
    student2: {
        id: "2323",
        name: "lewis"
    },
    student3: {
        id: "1212",
        name: "pint"
    }
}

我想將其轉換為一組學生對象,如下所示。 我如何使用可解碼來做到這一點?

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

也許這就是你想要的:

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)!)

抱歉,我讀錯了一點,所以我將再次擁有 go。

要制作一個數組,您可以執行以下操作:

struct Students: Codable {
    let students: [Student]
}

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

這足以將學生編碼成一個數組。 只需將 JSON 數據與Students一起傳遞。

您將不得不稍微編輯您的 JSON,如下所示:

{
    "students": [
        {
            id: "12",
            name: "jack",
        },
        {
            id: "2323",
            name: "lewis"
        },
        {
            id: "1212",
            name: "pint"
        }
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM