Home > Mobile >  How to return object from nested json
How to return object from nested json

Time:04-23

I have nested JSON and I'm trying to return an object and update UI. However, I can access properties only from Result array, but can't reach Step from AnalyzedInstactions.

Here are classes that represent data in the JSON. Generated it with https://app.quicktype.io

import UIKit

    class ResultArray: Codable {
    var results = [Result]() 
} 
class Result: Codable, CustomStringConvertible {

    var title: String = ""
    var image = ""
    var readyInMinutes: Int? = 0
    var servings: Int? = 0
    var cuisines = [String]()
    var dishTypes = [String]()
    var diets = [String]()
    var occasions = [String]()
    var analyzedInstructions = [AnalyzedInstruction]()
    
    var description: String {
        return "\nResults - Name: \(title), Summary: \(String(describing: readyInMinutes ?? nil)), \(String(describing: servings ?? nil)) "
    }
}
// MARK: - Steps

class AnalyzedInstruction: Codable {
    var name: String? = ""
    var steps = [Step]()
}

class Step: Codable {
    var number: Int = 0
    var step: String = ""
}

Here is my parse method

 private func parse(data: Data) -> [Result] {
        do {
            let decoder = JSONDecoder()
            let result = try decoder.decode(ResultArray.self, from: data)
            return result.results
        } catch {
            print("JSON Error: \(error)")
            return []
        }
    }

CodePudding user response:

try this simple code to access your steps from AnalyzedInstructions:

            let results: [Result] = parse(data: theData)
            
            if let firstResult = results.first {
                if let firstAnaInst = firstResult.analyzedInstructions.first {
                    for step in firstAnaInst.steps {
                        print("--> step.step: \(step.step)   step.number: \(step.number)")
                    }
                } else { print(" NO analyzedInstructions") }
            } else { print(" NO results") }

if you want all steps:

            for result in results {
                for anaInst in result.analyzedInstructions {
                    for step in anaInst.steps {
                        print("--> step.step: \(step.step)   step.number: \(step.number)")
                    }
                }
            }

PS: if appropriate, you may consider using struct instead of class for your json models.

  • Related