如何从其他模型数据创建JSON字符串?
我希望从数据中创建 json 字符串,但没有成功。
结果我正在数组中得到,然后我使用 For 循环传递给 AppointmentDownloadModel 进行 json 创建。
如何传递数据约会下载模型并创建 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 对象,然后将其编码为 Data(并转换为字符串(
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: $0)}
}
} 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)
}