如何在 Swift 5 中解析字典和数组 JSON

How to parse a dictionaray and array JSON in Swift 5

我正在尝试解析具有以下格式的 JSON 文件:

{
  "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"
      }
    ]
}

使用此代码:

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

但是我收到这个错误:

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

我该如何解决这个问题?谢谢!

使用此代码块创建您的模型,

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

您可以使用 this website 根据 json 数据轻松创建模型。

顺便说一下,您的 json 中缺少一个 }。如果您使用硬编码,请检查您的 json。