gpt4 book ai didi

ios - swift 4 : JsonSerialization of object with optional values fails

转载 作者:行者123 更新时间:2023-11-28 14:42:00 26 4
gpt4 key购买 nike

我有下一个结构:

struct PatientEntity{
let patientId: String
let firstName: String
let lastName: String
let gender: String
let birthDate: String?
let medicalDiagnosis: String?
let therapyDiagnosis: String?
let therapyGoals: String?
}

当我尝试将其序列化为 json 以便将其发送到服务器端时,由于 bithdate 上的 Optional word 而出现异常。我试图用下一个代码删除可选词,但没有成功:

if let bithDate = self.patientBithDateTextField.text {
newPatient: PatientEntity = PatientEntity(
patientId: self.patientIDTextField.text!,
firstName: self.patientNameTextField.text!,
lastName: self.patientLastNameTextField.text!,
gender: self.getSelectedGender(),
birthDate: bithDate,
medicalDiagnosis: nil,
therapyDiagnosis: nil,
therapyGoals: nil
)

...call API
}

我的序列化代码是:

urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])

其中参数值为:

case .createPatient(let newPatient):
return ["patient": newPatient]

输出打印如下:

The parametrs in POST string are: ["patient": PatientEntity(patientId: "fff", firstName: "rrr", lastName: "rrrr", gender: "Female", birthDate: Optional("2018-05-23"), medicalDiagnosis: nil, therapyDiagnosis: nil, therapyGoals: nil)]

要传递对象序列化权需要做什么?

异常(exception)是:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

最佳答案

如果您想检查有效的生日,可选绑定(bind)不是这样做的地方,我遇到了与您相同的错误。我建议您分离出从您的 View 中检索输入的代码。然后,测试 if bDate != nil 如下或类似。

struct PatientEntity: Encodable{
let patientId: String
let firstName: String
let birthDate: String?
}

var bDate: String? = "12-12-12"
var pID: String? = "2346"
var fName: String? = "gldlfk"

if bDate != nil {
let newPatient: PatientEntity = PatientEntity(patientId: pID!, firstName: fName!, birthDate: bDate)
let encoder = JSONEncoder()
let data = try! encoder.encode(newPatient)
print(String(data: data, encoding: .utf8)!)

}

输出:

{"firstName":"gldlfk","birthDate":"12-12-12","patientId":"2346"}

关于ios - swift 4 : JsonSerialization of object with optional values fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com