[英]Decoding Nested Arrays JSON Swift
我正在使用 JSON 文件來獲取我的應用程序中所需的數據。
[
{
"id": 1001,
"name": "Baguette",
"image": "baguette",
"category": "Bread",
"subheadline": "Le classique français.",
"portion": "Baguette",
"portions": "Baguettes",
"difficulty": "Facile 😁",
"recette": {
"quantity": [
200, 300, 10, 200
],
"unity": [
"g", "g", "g", "ml"
],
"ingredient": [
"Farine", "Eau", "Lait", "Beurre"
],
"ustensils": "Balance, robot de cuisine, coupe pâte, corne à patisserie souple, thermomètre de cuisson, lame de boulanger"
},
"recipesteps": [
{
"id": 1,
"quantityStep": [200, 300],
"unityStep": ["g", "g"],
"ingredientStep": ["Farine", "Eau"],
"ustensilStep": "Balance, ramequin, cuillère"
},
and so on…
]
然后我正在創建以下內容:
struct Bread: Codable, Identifiable {
var id: Int
var name: String
var image: String
var category: Category
var subheadline: String
var portion: String
var portions: String
var difficulty: String
var baking: CGFloat
var resting: CGFloat
var total: CGFloat
var isFavorite: Bool
var oventemperature: Int
var recipesteps: [RecipeSteps]
var recette: Recette
enum Category: String, CaseIterable, Codable {
case bread = "Bread"
case brioche = "Brioche"
case levain = "Levain"
}
struct Recette: Codable {
var quantity: [Int]
var unity: [String]
var ingredient: [String]
var ustensils: String
}
struct RecipeSteps: Codable {
var id: Int
var quantityStep: [Int]
var unityStep: [String]
var ingredientStep: [String]
var ustensilStep: String
}
}
最后解碼一切:
let breadData: [Bread] = load("BreadData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
要在我使用的代碼行中使用數據:
var bread: Bread
麻煩來了:我無法使用“RecipeSteps”中包含的數據。
例如,使用“面包”中的數據與
bread.name
並使用“bread.recette”中的數據與
var quantityInt: [Int] {
bread.recette.quantity
}
但是對“bread.recipesteps”做同樣的事情是行不通的。
我究竟做錯了什么?
recipeSteps 鍵在 JSON 中不存在,但 recipesteps 存在。
您的解碼密鑰不正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.