gpt4 book ai didi

ios - 如何在 swift 中将 JSON `null` 值传递给 `nil` 值?

转载 作者:行者123 更新时间:2023-11-29 05:33:19 24 4
gpt4 key购买 nike

我有这个 json,其中 hospitalNumber 具有值,并且在某些情况下它返回 null 值。 hospitalNumber 具有重要意义,因为它是 API 中端点所需参数的一部分。请参阅示例 json:

{
"responseMessage": "Request successful",
"data": [
{
"hospitalNumber": null,
"patientName": "Manual Entry",
"totalAmount": 10339.8000,
"manualEntry": true
},
{
"hospitalNumber": "1111111",
"patientName": "test patient",
"totalAmount": 932.5000,
"manualEntry": false
}
]
}

下面是我的端点 APIService,它将拉取上面的 json

typealias getPatientDetailsPerPayoutTaskCompletion = (_ patientDetailsPerPayout: [PatientPayoutDetails]?, _ error: NetworkError?) -> Void

//Patient procedure details per patient
//parameterName is .searchByHospitalNumber = "hospitalNumber"
static func getPatientDetailsPerPayout(periodId: Int, doctorNumber: String, parameterName: PatientParameter, hospitalNumber: String, manualEntry: Bool, completion: @escaping getPatientDetailsPerPayoutTaskCompletion) {


guard let patientDetailsPerPayoutURL = URL(string: "\(Endpoint.Patient.patientProcedureDetails)?periodId=\(periodId)&doctorNumber=\(doctorNumber)\(parameterName.rawValue)\(hospitalNumber)&manualEntry=\(manualEntry)") else {

completion(nil, .invalidURL)
return
}

let sessionManager = Alamofire.SessionManager.default
sessionManager.session.getAllTasks { (tasks) in
tasks.forEach({ $0.cancel() })
}

Alamofire.request(patientDetailsPerPayoutURL, method: .get, encoding: JSONEncoding.default).responseJSON { (response) in
print(patientDetailsPerPayoutURL)
guard HelperMethods.reachability(responseResult: response.result) else {
completion(nil, .noNetwork)
return
}

guard let statusCode = response.response?.statusCode else {
completion(nil, .noStatusCode)
return
}

switch(statusCode) {
case 200:
guard let jsonData = response.data else {
completion(nil, .invalidJSON)
return
}

let decoder = JSONDecoder()

do {
let patientDetailsPayout = try decoder.decode(RootPatientPayoutDetails.self, from: jsonData)
if (patientDetailsPayout.data?.isEmpty)! {
completion(nil, .noRecordFound)
} else {
completion(patientDetailsPayout.data, nil)
}
} catch {
completion(nil, .invalidJSON)
}

case 400: completion(nil, .badRequest)
case 404: completion(nil, .noRecordFound)
default:
print("**UNCAPTURED STATUS CODE FROM (getPatientDetailsPayout)\nSTATUS CODE: \(statusCode)")
completion(nil, .uncapturedStatusCode)
}
}
}

getPatientPayoutDetails函数

 func getPerPatientPayoutDetails(from: String, manualEntry: Bool) {
//SVProgressHUD.setDefaultMaskType(.black)
//SVProgressHUD.setForegroundColor(.white)
SVProgressHUD.setBackgroundColor(.lightGray)
SVProgressHUD.show(withStatus: "Retrieving Patient Procedures")

APIService.PatientList.getPatientDetailsPerPayout(periodId: doctorPayoutWeek[3].periodId!, doctorNumber: doctorNumber, parameterName: .selectedByHospitalNumber, hospitalNumber: from, manualEntry: manualEntry) { (patientPayout, error) in

guard let patientPerPayoutDetails = patientPayout, error == nil else {
if let networkError = error {
switch networkError {
case .noRecordFound:
let alertController = UIAlertController(title: "No Record Found", message: "You don't have current payment remittance", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
case .noNetwork:
let alertController = UIAlertController(title: "No Network", message: "\(networkError.rawValue)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
default:
let alertController = UIAlertController(title: "Error", message: "There is something went wrong. Please try again", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
}
}

SVProgressHUD.dismiss()
return
}
self.selectedPatientPayment = patientPerPayoutDetails
print(self.selectedPatientPayment)
SVProgressHUD.dismiss()
return
}
}

表格 View

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

switch indexPath.section {
case 0: break
case 1: break
case 2:

filteredPatient = indexPath.row
let selectedpatient = patientList[filteredPatient].hospitalNumber
let selectedEntry = patientList[filteredPatient].manualEntry
self.isBrowseAll = false
getPerPatientPayoutDetails(from: selectedpatient!, manualEntry: selectedEntry)
default: break
}
}

hospitalNumber为nil时,需要null字符串的端点

https://sample.com/openapi/getpatientpayoutdetails?periodId=579&doctorNumber=2866&hospitalNumber=null&manualEntry=true

如您所见,医院号码对于端点具有重要作用。我的问题是,一旦 tableView 重新加载,它就会正确显示数据,但是当我 didSelect 时,cell 带有 null HospitalNumber,我的应用程序崩溃并显示 Found nil error,因为 hospitalNumber 具有 null 值。希望您明白我想解释的内容,请帮助我。谢谢

最佳答案

您的Codable模型是正确的,您只需要guard-let/if-let来防止崩溃:

if let selectedpatient = patientList[filteredPatient].hospitalNumber, let selectedEntry = patientList[filteredPatient].manualEntry {
self.isBrowseAll = false
getPerPatientPayoutDetails(from: selectedpatient, manualEntry: selectedEntry)
}

更新:如果您想在 nil 的情况下创建 endPoint ,则使用 合并运算符:

getPerPatientPayoutDetails(from: selectedpatient ?? "null", manualEntry: selectedEntry)

关于ios - 如何在 swift 中将 JSON `null` 值传递给 `nil` 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319622/

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