0

I trying to parse some json using swift 4 and using decode. What I am confused is on the

Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

I am new to using decode and new to swift in general so I was wondering why I would be getting this error, I assume I am not really defining my structs the right way.

This is how I am defining my strucs

struct QuizDesc: Decodable {
    let title: String
    let desc: String
    let questions: [Questions]
}

struct Questions: Decodable {
    let text: String
    let answer: Int
    let answers: [Answers]
}

struct Answers: Decodable {
    let answerOne: String
    let answerTwo: String
    let answerThree: String
    let answerFour: String
}

And this is how I am using the decode function

let jsonString = "http://tednewardsandbox.site44.com/questions.json"

guard let url = URL(string: jsonString)else {return}

URLSession.shared.dataTask(with: url) { (data, response, err) in
    guard let data = data else{return}

    do {
        let quiz = try JSONDecoder().decode(QuizDesc.self, from: data)

        print(quiz.title)
    } catch let jsonErr {
        print("Error", jsonErr)
    }
}.resume()

This is the link I am using to extract the json data http://tednewardsandbox.site44.com/questions.json

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Zubair Amjad
  • 621
  • 1
  • 10
  • 29

1 Answers1

2

Your JSON is an array of QuizDesc. Change QuizDesc.self to [QuizDesc].self. Then rename quiz to quizzes.

rmaddy
  • 314,917
  • 42
  • 532
  • 579