如何从模型数据 Swift 创建 JSON 字符串?

How can I create JSON string from model data Swift?

如何从其他模型数据创建 JSON 字符串?

我想从数据中创建 json 字符串,但没有成功。

我得到的结果是数组,然后我使用 For Loop 传递给 AppointmentDownloadModel 以进行 json 创建。

如何传递数据 AppointmentDownloadModel 并创建 JSON 字符串。

数据接收模型:

struct ResponseData: Codable {

    let appointments : [Appointment]?
}


let decoder = JSONDecoder()
let response = try decoder.decode(ResponseData.self, from: result! as! Data)
self.appData = response.appointments
for everyApp in self.appData! {

}

想要将响应数据传递给此模型:

struct AppointmentDownloadModel: Codable{
    var appointmentModel: Appointment
    var progress: Int = 0
    var failedList: [Int: String] = [:]
    var isFinished: Bool = false
}

最后需要创建这个字符串:

{"appointmentModel":{"appointmentHour":"12:00","backgroundColorDark":"#556f7b","backgroundColorLight":"#cfd8dc","controlHour":"","date":"2020-06-01T12:00:00","heatingType":"b","id":15469622,"isProjectManual":false,"projectFirmName":"Miray Doğalgaz (Erhan Şahin)","projectName":"KÖKSAL ÇOŞKUN-+D1+D3+D5","projectType":"k","subTitle":"18137 902179436-18137-408352"},"failedResourceList":[],"isFinished":false,"progress":0}

以下解码 json 示例并创建新的 AppointmentDownloadModel 对象,然后将其编码为数据(并转换为字符串)

var models = [AppointmentDownloadModel]()

let decoder = JSONDecoder()
do {
    let response = try decoder.decode(ResponseData.self, from: data)
    if let appointments = response.appointments {
        models = appointments.map { AppointmentDownloadModel(appointmentModel: [=10=])}
    }
} catch {
    print(error)
}

let encoder = JSONEncoder()
do {
    let modelData = try encoder.encode(models)
    let jsonString = String(data: modelData, encoding: .utf8)
    print(jsonString)
} catch {
    print(error)
}