对于以下多种类型的json数组,有人可以告诉我如何为快速结构实现codable protocol
吗?
在以下json材质数组中,它可以是反射对象,视频或音符对象。
{
"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"
}
}
]
}
答案 0 :(得分:2)
如果您可以使用具有三个可选属性的Material
,这非常简单:
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)