我有一个如下格式的JSON,其中有一个学生对象。学生对象中列出了多名学生
Student {
student1: {
id: "12",
name: "jack",
},
student2: {
id: "2323",
name: "lewis"
},
student3: {
id: "1212",
name: "pint"
}
}我想把它转换成一个学生对象数组,如下所示。我如何使用decodable来做这件事?
struct student: Decodable {
let name: String
let id: String
}发布于 2020-08-11 18:58:08
也许这就是你想要的:
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)!)发布于 2020-08-11 18:44:48
抱歉,我读错了一点,所以我再试一次。
要创建一个数组,您可以执行类似以下操作:
struct Students: Codable {
let students: [Student]
}
struct Student: Codable {
let name: String
let id: String
} 这足以将学生编码到一个数组中。只需使用Students传递JSON数据。
您必须稍微编辑您的JSON,如下所示:
{
"students": [
{
id: "12",
name: "jack",
},
{
id: "2323",
name: "lewis"
},
{
id: "1212",
name: "pint"
}
]
}https://stackoverflow.com/questions/63356225
复制相似问题