【问题标题】:How can I create JSON string from model data Swift? [closed]如何从模型数据 Swift 创建 JSON 字符串? [关闭]
【发布时间】:2020-06-06 15:48:20
【问题描述】:

如何从其他模型数据创建 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}

【问题讨论】:

  • @vikingosegundo 更新了预约模型。
  • 为什么你的结构中的一切都是可选的?除非确实需要,否则不要将属性设为可选。
  • @JoakimDanielson 实际上数据来自后端,有时属性有值,有时没有。所以这就是我将它们设置为可选的原因。
  • 这能回答你的问题吗? How to convert JSON to String in ios Swift?

标签: ios json swift struct codable


【解决方案1】:

下面将解码 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)
}

【讨论】:

  • 首先谢谢你。我已经实现了你的代码。它给了我print(jsonString)[{\"isFinished\":false,\"appointmentModel\":{\"projectName\":\"HASAN ARSLAN\",\"id\":15473662,\"subTitle\":\"52792 \",\"appointmentHour\":\"09:00\",\"projectDistrict\":\"GEBZE\",\"projectFirmName\":\"Dipos 4 Test Firması\",\"date\":\"2020-06-01T09:00:00\",\"backgroundColorLight\":\"#cfd8dc\",\"backgroundColorDark\":\"#556f7b\",\"heatingType\":\"b\",\"isProjectManual\":false,\"controlHour\":\"\",\"projectType\":\"i\"},\"failedList\":{},\"progress\":0}]
  • 在我的问题中,请检查Final need to create this string: 我需要这样我怎样才能做到这一点
  • 你有那个字符串,只是当它被打印时你会看到所有的\
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多