【问题标题】:Swift 4: how to implement codable protocol for json array of different typesSwift 4:如何为不同类型的 json 数组实现可编码协议
【发布时间】:2017-12-29 14:19:11
【问题描述】:

有人能告诉我如何将codable protocol 实现为 swift 结构,用于以下多种类型的 json 数组吗?

在下面的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"
      }
    }
  ]
}

【问题讨论】:

    标签: json swift codable


    【解决方案1】:

    如果您可以使用具有三个可选属性的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)
    

    【讨论】:

    • 另一种“更难”的方式是使用枚举——但你需要为它实现 Codable 协议方法,例如类似this example code 的东西(基于@Gereon 的回答)
    • 非常感谢@MikhailChurbanov(:您的答案似乎更准确,但有什么区别,为什么要在这种情况下使用枚举而不是上述答案?
    • @Gereon,你觉得米哈伊尔的回答怎么样?
    • 完全同意@Gereon - 这完全取决于使用和个人品味。至于我,如果它不是太大且不太稳定(以某种方式),我会选择if let - 如果过度复杂化不会给你带来好处,那么它弊大于利。另一方面,enums 在复杂的动态(不断发展的)项目中更好——例如,如果你添加一个新类型来支持——对switch 语句的详尽要求将有助于自动找到你所在的所有地方需要处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2015-04-14
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多