提问者:小点点

如何在ios Swift中解析/映射数组中的对象


[
  {
    "department_id": "34",
    "department_name": "Anaesthesiology",
    "doctors_list": [
      {
        "doctor_id": "1",
        "hospital_id": "1",
       "dr_brief": "With "
      },
      {
        "doctor_id": "2",
        "hospital_id": "1",
      },
      {
        "doctor_id": "3",
        "hospital_id": "1",
       "dr_brief": "An MD in Anaesthesia "
      },
      {
        "doctor_id": "4",
        "hospital_id": "1",
        "dr_brief": "With MD"
      }
    ]
  },
  {
    "department_id": "38",
    "department_code": "CARD",
    "doctors_list": [
      {
        "doctor_id": "46",
        "hospital_id": "1",
       "dr_brief": "A DM in"
      },
      {
        "doctor_id": "47",
        "hospital_id": "1",
       "dr_brief": "A DM in  "
      },
      {
        "doctor_id": "48",
        "hospital_id": "1",
        "dr_brief": "With MS   "
      },
      {
        "doctor_id": "49",
        "hospital_id": "1",
        "dr_brief": "After completing his MBBS"
      },
      {
        "doctor_id": "50",
        "hospital_id": "1",
        "dr_brief": "With MBBS "
      },
      {
        "doctor_id": "51",
        "hospital_id": "1",
      },
      {
        "doctor_id": "52",
        "hospital_id": "1",
        "dr_brief": "An MD in Anaesthesiology "
      }
    ]
  }
]

共1个答案

匿名用户

对于映射对象:

 import Foundation

        // MARK: - department
        struct department: Codable {
            let departmentID, departmentName: String
            let doctorsList: [DoctorsList]
        
            enum CodingKeys: String, CodingKey {
                case departmentID = "department_id"
                case departmentName = "department_name"
                case doctorsList = "doctors_list"
            }
        }
        
        // MARK: - DoctorsList
        struct DoctorsList: Codable {
            let doctorID, hospitalID, drBrief: String?
        
            enum CodingKeys: String, CodingKey {
                case doctorID = "doctor_id"
                case hospitalID = "hospital_id"
                case drBrief = "dr_brief"
            }
        }
        
     typealias departments = [department]

对于json解码

let departments = try? newJSONDecoder().decode(departments.self, from: jsonData)

测试100%正常