再次在解码模型中发生typeMismatch JSONEncoder和JSONDecoder swift 5

问题描述 投票:0回答:1

我正在尝试更新模型中的值,并使用JSON操作进行解码和编码。我已经根据数据创建了模型。一切正常,但如果我再次解码模型,则会出现typeMismatch错误。我尝试过但没有成功。有人可以帮助我吗?

注意:原始JSON数据和编码数据可以看到区别。在缺少编码数据"appointments":标签中,我该如何处理并添加它。

原始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))
json swift nsjsonserialization jsondecoder jsonencoder
1个回答
3
投票

您的问题是您要编码

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

这是一个约会数组,然后尝试将jsonData解码为Dictionary

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)
© www.soinside.com 2019 - 2024. All rights reserved.