我正在尝试更新模型中的值并使用 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))