Home > Enterprise >  How to parse a dictionaray and array JSON in Swift 5
How to parse a dictionaray and array JSON in Swift 5

Time:04-20

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!

CodePudding user response:

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.

CodePudding user response:

Check out https://app.quicktype.io/

This website is such a time saver! Hope this was useful :)

  • Related