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

1 回答 1

2

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

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)
于 2020-01-27T14:54:37.823 回答