Reputation: 45
Can somebody enlighten me how to implement codable protocol
to swift structs, for the following json array of multiple types?
In the following json array of materials, it can be reflection object, video or note objects.
{
"materials": [
{
"reflection": {
"title": "3-2-1 reflection",
"description": "please reflect after today",
"questions": [
{
"question": "question 1",
"answer": "answer 1",
"answerImageUrl": "http://xxx"
},
{
"question": "question 1",
"answer": "answer 1",
"answerImageUrl": "http://xxx"
}
]
}
},
{
"video": {
"title": "the jungle",
"description": "please watch after today lesson",
"videoUrl": "http://"
}
},
{
"note": {
"title": "the note",
"description": "please read after today lesson"
}
}
]
}
Upvotes: 2
Views: 608
Reputation: 17844
If you can live with a Material
that has three optional properties, this is quite straightforward:
struct Response: Codable {
let materials: [Material]
}
struct Material: Codable {
let reflection: Reflection?
let video: Video?
let note: Note?
}
struct Video: Codable {
let title, description, videoUrl: String
}
struct Reflection: Codable {
let title, description: String
let questions: [Question]
}
struct Question: Codable {
let question, answer, answerImageUrl: String
}
struct Note: Codable {
let title, description: String
}
let response = JSONDecoder().decode(Response.self, from: data)
Upvotes: 2