Reputation: 107
I have a JSON of following format in which there is a student object. student object has multiple students listed in it
Student {
student1: {
id: "12",
name: "jack",
},
student2: {
id: "2323",
name: "lewis"
},
student3: {
id: "1212",
name: "pint"
}
}
I would like to convert this into an array of student objects as shown below. How do i do this using decodable?
struct student: Decodable {
let name: String
let id: String
}
Upvotes: 0
Views: 239
Reputation: 1274
Perhaps this is what you want:
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)!)
Upvotes: 2
Reputation: 386
Apologies, I've misread this a bit so I'll have a go again.
To make an array you could do something like the following:
struct Students: Codable {
let students: [Student]
}
struct Student: Codable {
let name: String
let id: String
}
This is enough to code the students into an array. Simply pass the JSON data with Students
.
You will have to edit your JSON slightly, like this:
{
"students": [
{
id: "12",
name: "jack",
},
{
id: "2323",
name: "lewis"
},
{
id: "1212",
name: "pint"
}
]
}
Upvotes: 0