简体   繁体   中英

Decoding Nested Arrays JSON Swift

I'm using a JSON File to get the data I need in my app.

[
    {
        "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…

]

I'm then creating the following:

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
        }
    }

And finally decoding everything:

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)")
    }
}

To use the Data in my lines of code I'm using:

var bread: Bread

Here comes the trouble: I'm unable to use the data contained in "RecipeSteps".

For example, using the data in "Bread" works with

bread.name

and using the data in "bread.recette" works with

    var quantityInt: [Int] {
        bread.recette.quantity
    }

but doing the same for "bread.recipesteps" doesn't work.

What am I doing wrong?

The recipeSteps key does not exists in JSON, but recipesteps exists.

Your decoding key is not correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM