json - 如何在 Swift 中使用带有递增键的自定义解码器 init 来解析 JSON

标签 json swift decodable

我有一些膳食 json,我想将其转换为 MealData 结构

let randomMealJson = """
{
    "meals": [{
        "idMeal": "52812",
        "strMeal": "Beef Brisket Pot Roast",
        "strDrinkAlternate": null,
        "strCategory": "Beef",
        "strArea": "American",
        "strInstructions": "Meal instructions",
        "strMealThumb": "https://www.themealdb.com/images/media/meals/ursuup1487348423.jpg",
        "strTags": "Meat",
        "strYoutube": "https://www.youtube.com/watch?v=gh48wM6bPWQ",
        "strIngredient1": "Beef Brisket",
        "strIngredient2": "Salt",
        "strIngredient3": "Onion",
        "strIngredient4": "Garlic",
        "strIngredient5": "Thyme",
        "strIngredient6": "Rosemary",
        "strIngredient7": "Bay Leaves",
        "strIngredient8": "beef stock",
        "strIngredient9": "Carrots",
        "strIngredient10": "Mustard",
        "strIngredient11": "Potatoes",
        "strIngredient12": null,
        "strIngredient13": null,
        "strIngredient14": null,
        "strIngredient15": null,
        "strIngredient16": null,
        "strIngredient17": null,
        "strIngredient18": null,
        "strIngredient19": null,
        "strIngredient20": null,
        "strMeasure1": "4-5 pound",
        "strMeasure2": "Dash",
        "strMeasure3": "3",
        "strMeasure4": "5 cloves",
        "strMeasure5": "1 Sprig",
        "strMeasure6": "1 sprig ",
        "strMeasure7": "4",
        "strMeasure8": "2 cups",
        "strMeasure9": "3 Large",
        "strMeasure10": "1 Tbsp",
        "strMeasure11": "4 Mashed",
        "strMeasure12": "",
        "strMeasure13": "",
        "strMeasure14": "",
        "strMeasure15": "",
        "strMeasure16": "",
        "strMeasure17": "",
        "strMeasure18": "",
        "strMeasure19": "",
        "strMeasure20": "",
        "strSource": "http://www.simplyrecipes.com/recipes/beef_brisket_pot_roast/",
        "dateModified": null
    }]
}
"""

这是我想要制作的结构...

struct MealData: Decodable {
    let meals: [Meal]
}

struct Meal: Decodable {
    let items: [Item]
}

extension Meal {
    struct Item: Decodable {
        let ingredient: String
        let measure: String
    }
}

extension Meal {
    init(from decoder: Decoder) throws {
//        var items: [Item] = (0...20).map { num in      
//           what to do here?
//        }
    }
}

我想详细了解成分和措施,并根据它们创建一个 Meal.Item,但我不知道如何实现这一点。可以按照我在代码中指示的方式吗?

最佳答案

遵循@joakim-danielson 的回答。您可以在 init(from:) 初始化程序中执行相同的操作,就像您的初衷一样。

只需将每份Meal的成分和尺寸解码为[String: String?]并编写您的自定义Item:

extension Meal {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        
        let mealDict = try container.decode([String: String?].self)
        var index = 1
        var items = [Item]()
        while
            let ingredient = mealDict["strIngredient\(index)"] as? String,
            let measure = mealDict["strMeasure\(index)"] as? String,
            !measure.isEmpty
        {
            items.append(Item(ingredient: ingredient, measure: measure))
            index += 1
        }
        self.items = items
    }
}

关于json - 如何在 Swift 中使用带有递增键的自定义解码器 init 来解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64265867/

相关文章:

json - AWS Lambda 错误 : 'Could not parse request body into json ' when url parameter contains JSON array

arrays - `removeLast` 会 swift 减少数组的容量吗?

ios - 类型 'Model' 不符合协议(protocol) 'Decodable'/Encodable

Swift 可编码多种类型

swift - 可解码符合枚举类型的属性

python - Flask 中的基本身份验证仅适用于一名用户

javascript - 从要在 D3 中使用的 JSON 文件访问 ids

使用 cURL + JSON Lib 的 C++ POST 请求

swift - 我可以创建一个 AppDelegate 实例吗?

ios - 使用唯一键快速合并字典