Home > Software engineering >  How to decode a Json result after Post http request but with no quotation marks?
How to decode a Json result after Post http request but with no quotation marks?

Time:03-16

after this http request and struct together:

 struct LoginDataModel : Codable {
    let token: String
    let uid: String
    enum CodingKeys: String, CodingKey {
        case token = "token"
        case uid = "uid"
    }
}


func LoginRequest() {
      
      // declare the parameter as a dictionary that contains string as key and value combination. considering inputs are valid
      
        let parameters:Dictionary<String, Any> = [
              "data" : [
                  "email" : email,
                  "password" : password,
                  "token" : token,
               
                  ]
          ]
       
      
      // create the url with URL
      let url = URL(string: "https://us-central1-space-book-4f180.cloudfunctions.net/userLogin")! // change server url accordingly
      
      // create the session object
      let session = URLSession.shared
      
      // now create the URLRequest object using the url object
      var request = URLRequest(url: url)
      request.httpMethod = "POST" //set http method as POST
      request.httpBody = parameters.percentEncoded()
      // add headers for the request
      request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // change as per server requirements
      request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
      
      do {
        // convert parameters to Data and assign dictionary to httpBody of request
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
      } catch let error {
        print(error.localizedDescription)
        return
      }
      
      // create dataTask using the session object to send data to the server
      let task = session.dataTask(with: request) { data, response, error in
        
        if let error = error {
          print("Post Request Error: \(error.localizedDescription)")
          return
        }
        
          
        // ensure there is valid response code returned from this HTTP response
        guard let httpResponse = response as? HTTPURLResponse,
              (200...299).contains(httpResponse.statusCode)
        else {
          print("Invalid Response received from the server")
          return
        }
        
        // ensure there is data returned
        guard let responseData = data else {
          print("nil Data received from the server")
          return
        }
        
        do {
          // create json object from data or use JSONDecoder to convert to Model stuct
            if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? Dictionary<String,Any>{
            print(jsonResponse)
              let decoder = JSONDecoder()
              do {
                  let loginResponse = try decoder.decode(LoginDataModel.self, from: responseData)
                  AuthenticationManager.shared.saveToken(loginDataModel: loginResponse)
                  AuthenticationManager.shared.saveUid(loginDataModel: loginResponse)
                  print("Users list :", loginResponse.uid )
                  } catch {
                   print(error)
               }
            // handle json response
          } else {
            print("data maybe corrupted or in wrong format")
            throw URLError(.badServerResponse)
          }
        } catch let error {
          print(error.localizedDescription)
        }
      }
      // perform the task
      task.resume()
    }

i got this response in the terminal:

["response": {
    token = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRCME0yQSJ9.eyJpc3MiOiJodHRwczovL3Nlc3Npb24uZmlyZWJhc2UuZ29vZ2xlLmNvbS9zcGFjZS1ib29rLTRmMTgwIiwiYXVkIjoic3BhY2UtYm9vay00ZjE4MCIsImF1dGhfdGltZSI6MTY0NzQxNTEyMCwidXNlcl9pZCI6IkY0UjZWQXhJZVhNU2VJc1JQdkZxQlFPQWxWSTIiLCJzdWIiOiJGNFI2VkF4SWVYTVNlSXNSUHZGcUJRT0FsVkkyIiwiaWF0IjoxNjQ3NDE1MTIwLCJleHAiOjE2NDc4NDcxMjAsImVtYWlsIjoiYXJAeTc2LmlvIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsiYXJAeTc2LmlvIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifX0.U1buRHJstnwCNHjn4dDhwMRwm-Or6FF-F4KeO_GNQpox0IPCVFsdd_ko0lyXIle34Hs0pFDn-gEUe-VA9hXb96afnEZbiBkf-2ef_sOSwt6hEbW53vNbk784ws8dC340rSemV4HUwwN_PNZswXcXR_tdKFqVAGWJE3yKOu9KOcrcDtzNQWoE_Kf2LDLNEWkWW_uS7CQ3mjF9QvTt9-y80qCd-SKsv0OVoRdN4LTHcoFG-x6sCb5QkiO1ZJ6Z2cnO1yE4-RB0z0XGCH6Mnqi_iQtPBsmcGRUw3Ku7XuFaI7M9YnhUFeW6nfc3d5q6LpjvLV2wSXh3D0JRsIRiN-yEYw";
    uid = F4R6VAxIeXMSeIsRPvFqBQOAlVI2;
}]

but this response is ((((unquoted)))) ! how can i parse this response so that i can save the uid and token and use them later in the app , i need a way for parsing it, please can't find a way to do it ! and thank you so much

CodePudding user response:

According to the response you show, you should be decoding this:

 let loginResponse = try decoder.decode(LoginResponse.self, from: responseData)

where you declare:

struct LoginResponse : Codable {
       let response: LoginDataModel
   }
  • Related