【发布时间】:2021-07-14 21:55:07
【问题描述】:
我正在开发一个食谱应用程序,我能够解析 json 数据,但我坚持如何实现每个食谱的一部分:
recipe.json
附上食谱的示例部分:
{
"title": "Crumble",
"image" : "crumble",
"description": "Delicious!",
"prepTime": " 7 minutes",
"cookTime": " 3 minutes",
"servings": 4,
"summary": [ //<--- Need help with this section!
{"rating":"5"},
{"serves":"4"},
{"preparation":"7 minutes"},
{"cooking" : "3 minutes"}
],
"ingredients": [
{"name": "Apple Pie Filling, peeled and thinly-sliced", "num": 800, "unit": "grams"},
{"name": "Ground Cinnamon", "num": 1, "unit": "teaspoon"}
{"name": "Double Cream, to serve"}
],
"directions":
[
"Combine apple, cinnamon and lemon rind in a bowl.",
"Sprinkle muesli on top of apple mixture. "
]
},
配方模型
class Recipe: Identifiable, Decodable {
var id:UUID?
var title: String
var image: String
var description: String
var prepTime: String
var cookTime: String
var servings: Int
var summary: [String:String]
var ingredients: [Ingredient]
var directions: [String]
}
类成分:可识别,可解码{
var id:UUID?
var name:String
var num:Int?
var denom:Int?
var unit:String?
}
从上面的 .json 文件中,我创建了我的模型。
我能够解析和检索上述所有内容,“摘要”部分除外。
如果我使用上述概要信息运行我的应用程序,我会收到此错误:
typeMismatch(Swift.Dictionary
, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: “Index 0”, intValue: 0), CodingKeys(stringValue: “summary”, intValue : nil)], debugDescription: “期望解码 Dictionary 但找到了一个数组。”, 底层错误: nil))
但是,如果我在我的 Model - Recipe.swift 文件中注释掉“SUMMARY”信息,则在解析本地 json 文件时不会崩溃,并且会收到所有其他信息。
我在我的模型中写不正确吗?我怎样才能让它工作,这样我就可以在不崩溃的情况下为我的应用访问它?
【问题讨论】: