0

I'm trying to parse a JSON file with the following format:

{
  "OnDemand" : {
    "program" : [
      {
        "Sunday" : "https://example1.m4a",
        "SundaySharePage" : "https://example1",
        "name" : "Example 1",
        "weekdays" : "Sunday"
      },
      {
        "Monday" : "https://example2.m4a",
        "MondaySharePage" : "https://example2",
        "name" : "Example 2",
        "weekdays" : "Monday"
      }
    ]
}

Using this code:

struct AllPrograms: Codable {
    let OnDemand: [Dictionary<String,String>: Programs]
}

struct Programs: Codable {
    let program:Array<String>
                        
}

func parsePrograms (urlString:String) {
    if let url = URL(string: urlString) {
       URLSession.shared.dataTask(with: url) { data, response, error in
       if let data = data {
           let jsonDecoder = JSONDecoder()
           do {
               let parsedJSON = try jsonDecoder.decode(AllPrograms.self, from: data)
               print(parsedJSON.OnDemand)
           } catch {
               print(error)
           }
       }
       }.resume()
    }
}

But I'm getting this error:

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "OnDemand", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

How do I fix this? Thank you!

2
  • 2
    app.quicktype.io Commented Apr 20, 2022 at 14:03
  • Thanks for the website! Commented Apr 20, 2022 at 14:11

1 Answer 1

1

use this code block to create your Model,

import Foundation

// MARK: - AllPrograms
struct AllPrograms: Codable {
    let onDemand: OnDemand

    enum CodingKeys: String, CodingKey {
        case onDemand = "OnDemand"
    }
}

// MARK: - OnDemand
struct OnDemand: Codable {
    let program: [Program]
}

// MARK: - Program
struct Program: Codable {
    let sunday, sundaySharePage: String?
    let name, weekdays: String
    let monday, mondaySharePage: String?

    enum CodingKeys: String, CodingKey {
        case sunday = "Sunday"
        case sundaySharePage = "SundaySharePage"
        case name, weekdays
        case monday = "Monday"
        case mondaySharePage = "MondaySharePage"
    }
}

You can use this website for easly creating models according to json data.

By the way in your json there is one } missing. check your json if you use hard coded.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.