有没有一种方法可以在Swift中仅部分地从JSON创建对象?

时间:2019-11-07 15:11:15

标签: json swift mapping partial

我正在创建一个SwiftUI抽认卡应用程序,使用Codable并遵循苹果公司在其landmarks tutorial app上展示的用于导入JSON数据以创建对象数组的技术。

但是,不需要从JSON加载我的抽认卡对象的两个属性,如果我可以分别初始化这些值而不是从JSON加载它们,则可以最小化JSON文件中所需的文本。问题是我无法正确地加载JSON数据,除非它准确地映射到所有对象的属性,即使缺少的属性是用值硬编码的。

这是我的对象模型:

import SwiftUI

class Flashcard: Codable, Identifiable {
    let id: Int
    var status: Int
    let chapter: Int
    let question: String
    let answer: String
    let reference: String
}

这是有效的JSON:

[
  {
    "id": 1,
    "status": 0,
    "chapter": 1,
    "question": "This is the question",
    "answer": "This is the answer",
    "reference": "This is the reference"
  }
  //other card info repeated after with a comma separating each
]

我不想在JSON中不必要地列出“ id”和“ status”,而是希望将模型更改为以下形式:

import SwiftUI

class Flashcard: Codable, Identifiable {
    let id = UUID()
    var status: Int = 0

    //only load these from JSON:
    let chapter: Int
    let question: String
    let answer: String
    let reference: String
}

...然后从理论上讲,我应该能够从JSON中消除“ id”和“ status”(但我不能)。有没有一种简单的方法可以防止JSON错误无法完全映射到对象?

2 个答案:

答案 0 :(得分:0)

是的,您可以通过在Codable类上设置编码键来实现。只需将不需要的内容从json中删除即可。

class Flashcard: Codable, Identifiable {
    let id = UUID()
    var status: Int = 0
    let chapter: Int
    let question: String
    let answer: String
    let reference: String

    enum CodingKeys: String, CodingKey {
        case chapter, question, answer, reference
    }
}

HackingWithSwift在Codable here上有一篇很棒的文章

答案 1 :(得分:0)

您可以使用CodingKeys定义要从JSON中提取哪些字段。

class Flashcard: Codable, Identifiable {
    enum CodingKeys: CodingKey {
       case chapter
       case question
       case answer
       case reference
    }

    let id = UUID()
    var status: Int = 0

    //only load these from JSON:
    let chapter: Int
    let question: String
    let answer: String
    let reference: String
}

The docuemntation has a good explanation (for once) of this under `Encoding and Decoding Custom Types`