Swift - Expected to decode Array<Any> but found a dictionary instead.”, underlyingError: nil

Swift - Expected to decode Array<Any> but found a dictionary instead.”, underlyingError: nil

我正在尝试为我的应用程序解码一些 json,我通常这样做。

我的结构;

struct RequestTypes: Codable {
      let MerchRequestTypeID: Int?
      let TypeName: String?
      let LayoutID: Int?

   private enum CodingKeys: Int, CodingKey {
       case MerchRequestTypeID
       case TypeName
       case LayoutID
       }
}

并解码;

func downloadRequestTypesJson(){
    guard let gitUrl = URL(string: "URL") else { return }
    URLSession.shared.dataTask(with: gitUrl) { (data, response
        , error) in
        guard let data = data else { return }
        do {
            let decoder = JSONDecoder()
            let RequestData = try decoder.decode(Array<RequestTypes>.self, from: data)
            DispatchQueue.main.sync {
                print(RequestData[0].MerchRequestTypeID)
                print(RequestData[1].MerchRequestTypeID)
                print(RequestData[2].MerchRequestTypeID)
            }
        } catch let err {
            print("Err", err)
        }
        }.resume()
}

这适用于以下 json;

[
   {
     "MerchRequestTypeID": 1,
     "TypeName": "Stok",
     "LayoutID": 1
   },
   {
     "MerchRequestTypeID": 2,
     "TypeName": "Stand",
     "LayoutID": 2
   },
   {
     "MerchRequestTypeID": 3,
     "TypeName": "Eğitim",
     "LayoutID": 2
   }
]

但现在我需要解码这个 json 并且我得到 Expected to decode Array but found a dictionary instead.错误;

{
  "RequestTypes": [
   {
     "MerchRequestTypeID": 1,
     "TypeName": "Stock",
     "LayoutID": 1
   },
   {
     "MerchRequestTypeID": 2,
     "TypeName": "Stand",
     "LayoutID": 2
   },
   {
     "MerchRequestTypeID": 3,
     "TypeName": "Education",
     "LayoutID": 2
   }
  ]
}

无法找到执行此操作的正确方法。感谢任何帮助。

编辑: 我是 Swift 的初学者。我想知道如何解码第二个 json 以及如何到达它的元素。

那是因为您正在尝试使用“RequestTypes”属性 而不是数组来解码 JSON 对象。一种解决方案是为此数据结构创建一个新结构并使用它来解码您的 JSON:

struct RequestTypesContainer: Codable {
    let RequestTypes : [RequestTypes]

    private enum CodingKeys: String, CodingKey {
       case RequestTypes
    }
}

然后:

let RequestData = try decoder.decode(RequestTypesContainer.self, from: data)