如何快速解决使用Alamofire从API提取数据中的无效json问题?

时间:2019-07-30 02:32:26

标签: ios json swift api alamofire

我的代码需要帮助。下面的json是我从postman得到的原始答复。

旧格式

{
   "totalCreditedAmount": 2898.3000,
   "periodId": 566,
   "periodDate": "4/26/2019"
}

因此,我在下面创建了API服务代码。运行顺利。

APIService

 struct DoctorLatestCreditedAmount {
   typealias getLatestCreditedAmountTaskCompletion = (_ latestCreditedAmount: CurrentRemittance?, _ error: NetworkError?) -> Void

  static func getLatestCreditedAmount(doctorNumber: String, completion: @escaping getLatestCreditedAmountTaskCompletion) {

        guard let latestCreditedAmountURL = URL(string: "\(Endpoint.LatestCreditedAmount.latestCreditedAmount)/\(doctorNumber)") else {
            completion(nil, .invalidURL)
            return
        }

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

        Alamofire.request(latestCreditedAmountURL, method: .get, encoding: JSONEncoding.default).responseJSON { (response) in
            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 currentCreditedAmount = try decoder.decode(CurrentRemittance.self, from: jsonData)
                completion(currentCreditedAmount, nil)
            } catch {
                completion(nil, .invalidJSON)
                }

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

        }

    }

但是当json方面在响应方面有所变化。 json格式已更改,现在使用上面的APIService遇到错误。它显示为invalidjson,因为下面是新的json格式。

新格式

 {
   "responseMessage": "Request successful",
    "data": {
         "totalCreditedAmount": 2898.3000,
         "periodId": 566,
         "periodDate": "4/26/2019"
   }
}

已编辑:getTotalCreditedAmount

var currentRemittance: CurrentRemittance!

func getTotalCreditedAmount(doctorNumber: String) {
   windlessSetup()
   APIService.DoctorLatestCreditedAmount.getLatestCreditedAmount(doctorNumber: doctorNumber) { (remittanceDetails, error) in
       guard let creditedAmountDetails = remittanceDetails, 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))
                    self.present(alertController, animated: true, completion: nil)
               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)
               }
           }
           self.creditedView.windless.end()
           self.remittanceView.windless.end()
           return
       }
       self.currentRemittance = creditedAmountDetails
       self.showLatestTotalCreditedAmount()
       self.creditedView.windless.end()
       self.remittanceView.windless.end()
       return
   }

}

遇到错误 Breakpoint Image

我的问题是,如何更改 APIService 的代码,以使其与我得到的正确的新json格式匹配。由于我习惯于使用相同的“旧”格式,因此我很难过。我真的是新手,也确实需要帮助。希望你能给我一些时间。

2 个答案:

答案 0 :(得分:1)

您需要


// MARK: - Welcome
struct Root: Codable {
    let responseMessage: String
    let data: CurrentRemittance
}

// MARK: - DataClass
struct CurrentRemittance: Codable {
    let totalCreditedAmount: Double
    let periodId: Int
    let periodDate: String 
}

解码

 let res = try decoder.decode(Root.self, from: jsonData) 
 print(res.data)

答案 1 :(得分:0)

尝试以下代码,它对我的​​数据数组有效:

# Configure the Microsoft Azure Active Directory Provider
provider "azuread" {
  version = "~> 0.3"
}

# Create an application
resource "azuread_application" "example" {
  name = "${var.prefix}-app-service"
  homepage                   = "https://${var.prefix}-app-service"
  identifier_uris            = ["https://${var.prefix}-app-service"]
  reply_urls                 = ["https://${var.prefix}-app-service.azurewebsites.net/.auth/login/aad/callback"]
  available_to_other_tenants = false
  oauth2_allow_implicit_flow = true

}