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

标签 ios json swift alamofire

我有这个 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/

相关文章:

ios - 带有平移手势的 CATransition Cube

ios - 如果我想为 UIButton 创建更大的点击区域,我应该覆盖 hitTest : or pointInside:?

python - 使用 Python 进行简单的 JSON 编码

swift - UILabel 未正确更改文本

ios - iOS:将对象设置为nil时,ARC和MRC有什么区别?

ios - 使用我自己的 UICollectionViewFlowLayout 子类滚动时,UICollectionView 项目消失

ios - 启用 guard malloc 时出现奇怪的错误

javascript - Angularjs orderby 对象键

javascript - 将 id 从 json 传递到 js 到对话框弹出

ios - Swift 3 - UITableView 在 UIScrollView 中被截断