我的 Xcode 项目中有一个 JSON 文件。让我们以此为例:
{ "shifts": [
{"name": "Mary",
"role": "Waiter"},
{"name": "Larry",
"role": "Cook"}
]
}
在我的 JSONManager.swift 中,我有一些类似的内容:
struct Shift: Codable {
let role, name: String
static let allShifts: [Shift] = Bundle.main.decode(file: "shifts.json")
}
extension Bundle {
func decode<T: Decodable>(file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Could not find \(file) in the project")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Could not load \(file) in the project")
}
let decoder = JSONDecoder()
guard let loadedData = try? decoder.decode(T.self, from: data) else {
fatalError("Could not decode \(file) in the project")
}
return loadedData
}
}
我一直遇到错误:
fatalError(“无法解码项目中的(文件)”)
我想知道是否是因为 JSON 格式不正确或者为什么它无法从 JSON 文件中解码 JSON。
暂时看一下 JSON 结构。
您有一个名为
shifts
的元素,它是其他元素的任何数组,但您的代码似乎试图加载仅包含子元素的结构。
相反,您需要一个外部
struct
,其中包含子 struct
,例如...
struct Shift: Codable {
let role, name: String
}
struct Shifts: Codable {
let shifts: [Shift]
}
然后,在解码内容时,您将使用父级
struct
作为初始源类型...
extension Bundle {
func decode<T: Decodable>(file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Could not find \(file) in the project")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Could not load \(file) in the project")
}
let decoder = JSONDecoder()
guard let loadedData = try? decoder.decode(T.self, from: data) else {
fatalError("Could not decode \(file) in the project")
}
return loadedData
}
}
let shifts: Shifts = Bundle.main.decode(file: "shifts.json")
我在游乐场测试了这个,效果很好。
可能可以在不需要“父”的情况下解码结构
struct
,但这对我有用。
我改正了自己的错误。我不需要
{ "shifts": }
在我的 JSON 中