Swift 4:具有可选值的对象的JsonSerialization失败

时间:2018-05-23 11:19:55

标签: ios swift serialization alamofire swift4

我有下一个结构:

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上的可选单词。我尝试用下一个代码删除可选单词,但没有运气:

 if let bithDate = self.patientBithDateTextField.text {
            let 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]

输出打印如下:

  

POST字符串中的参数是:["患者":   PatientEntity(patientId:" fff&#34 ;, firstName:" rrr",   lastName:" rrrr",性别:"女性",birthDate:可选(" 2018-05-23"),   medicalDiagnosis:nil,therapyDiagnosis:nil,therapyGoals:nil)]

为了传递对象的序列化,有什么必要做的?

例外是:

  

由于未捕获的异常而终止应用   ' NSInvalidArgumentException',原因:' JSON写入中的无效类型   (_SwiftValue)'

3 个答案:

答案 0 :(得分:1)

如果您想检查有效的生日,可选的绑定不是这样做的地方,我得到了与您相同的错误。我建议你将从视图中检索输入的代码分开。然后,针对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"}

答案 1 :(得分:0)

您的Paramters应该是StringNSNumberArrayDictionaryNSNull的实例,而不是PatientEntity的对象输入PatientEntity转换为dictionary

所以参数应该是那样的

["patient": ["patientId": "fff", "firstName": "rrr", "lastName": "rrrr", "gender": "Female", "birthDate": Optional("2018-05-23"), "medicalDiagnosis": nil, vtherapyDiagnosis": nil, "therapyGoals": nil]]

答案 2 :(得分:0)

如果PatientEntity的字段与服务器期望的字段完全对应,那么只需将其符合Encodable:

struct PatientEntity: Encodable {...

以这种方式序列化:

urlRequest.httpBody = try JSONEncoder().encode(parameters)