Swift 4:如何为不同类型的json数组实现可编码协议

时间:2017-12-29 14:19:12

标签: json swift codable

对于以下多种类型的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"
      }
    }
  ]
}

1 个答案:

答案 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)