我正在创建一个 SwiftUI 抽认卡应用程序,使用 Codable 并遵循 Apple 用他们的 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 未完全映射到对象的错误?
最佳答案
是的,您可以通过在 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
关于json - 有没有办法在 Swift 中仅从 JSON 部分创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58751701/