再次解码模型中的类型不匹配 JSONEncoder 和 JSONDecoder swift 5

typeMismatch in Decoding model again JSONEncoder and JSONDecoder swift 5

我正在尝试更新模型中的值并使用 JSON 操作解码和编码。我根据数据创建了模型。一切正常,但如果我再次解码我的模型,它会给我 typeMismatch 错误。我试过但没有成功。谁能帮帮我?

Note: Original JSON Data & and Encoded Data print you can see the difference. In Encoded data "appointments": tag is missing how can I handle this and add this.

原始JSON数据:

{
  "appointments": [
    {
      "id": 15473454,
      "isProjectManual": false,
      "projectType": "i",
      "appointmentHour": "05:04",
      "projectName": "Farid Farjad",
      "warmingType": "b",
      "subTitle": "4874345 ",
      "projectDistrict": "Çay",
      "projectFirmName": "Test Firması",
      "controlHour": "",
      "date": "2019-12-26T05:04:00",
      "backgroundColorLight": "#cfd8dc",
      "backgroundColorDark": "#556f7b"
    }
  ],
  "isSuccess": true,
  "message": "İşlem Başarılı.",
  "statusCode": 1
}

型号:

struct ResponseData: Codable {

    let appointments : [Appointment]?
    let isSuccess : Bool?
    let statusCode : Int?
    let message : String?

}

struct Appointment : Codable {

    let appointmentHour : String?
    let backgroundColorDark : String?
    let backgroundColorLight : String?
    let controlHour : String?
    let date : String?
    let id : Int?
    let isProjectManual : Bool?
    let projectDistrict : String?
    let projectFirmName : String?
    let projectName : String?
    let projectType : String?
    let subTitle : String?
    let warmingType : String?
}

编码:

var Appdata : [Appointment]? 

let jsonData = try! JSONEncoder().encode(self.Appdata)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)

编码打印

[
  {
    "projectName": "Farid Farjad",
    "id": 15473454,
    "subTitle": "4874345 ",
    "appointmentHour": "05:04",
    "projectDistrict": "Çay",
    "projectFirmName": "Test Firması",
    "date": "2019-12-26T05:04:00",
    "backgroundColorLight": "#cfd8dc",
    "backgroundColorDark": "#556f7b",
    "isProjectManual": false,
    "controlHour": "",
    "projectType": "i",
    "warmingType": "b"
  }
]

解码码

let dec = JSONDecoder()
let resp = try dec.decode(ResponseData.self, from: jsonData)
print(resp)

解码打印

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

您的问题是您正在尝试编码

var Appdata : [Appointment]? 
let jsonData = try! JSONEncoder().encode(self.Appdata)

这是一个约会数组,然后尝试将jsonData解码成字典

let dec = JSONDecoder()
let resp = try dec.decode(ResponseData.self, from: jsonData)

您可以更改编码或解码。

编码

将您的编码更改为以下。

var Appdata : ResponseData?

用法就是你想怎么用。

let resp = try dec.decode(ResponseData.self, from: jsonData)

解码

如果您希望使用当前的编码功能,则需要按如下方式进行解码。

let resp = try dec.decode([Appointment].self, from: jsonData)