I would like convert json string to an Object with generics kind in swift. tecnically i’ve a GenricResponse class and this class has a Generic propertie, on this propertie it might be the JsonWebToken class (JwtResponse). JwtResponse has 2 different clases (JwtDecode and Usuarios). when this system is attempting to transform the information to object i get the error message for the conversion: Didn’t decode response into the given kind
as i perceive the json is the same as the item construction: GenericResponse
that is my class GenericResponse
import Basis
import SwiftUI
class GenericResponse<T: Codable>: Codable {
var message: String?;
var response: String?;
var information: T?;
}
JwtResponse class:
import Basis
import Swift
struct JwtResponse: Codable {
var jwtEncode: String;
var jwtDecode: JwtDecode;
var usuario: Usuarios;
}
JwtDecode class:
import Basis
import SwiftUI
class JwtDecode : Codable {
var iat: Int;
var iss: String;
var nbf: Int;
var exp: Int;
var e-mail: String;
var username: String;
}
class Usuarios:
import Basis
import Swift
class Usuarios: Codable {
var usrs_id: Int?;
var usrs_nombre: String?;
var usrs_numero_asoiciado : Int?;
var usrs_telefono : Int?;
var usrs_sexo : Int?;
var usrs_password: String?;
var usrs_usuario: String?;
var usrs_correo: String?;
var usrs_activation: String?;
var usrs_status: Int?;
var usrs_status_active: Int?;
var usrs_plantel: Int?;
var usrs_psts_id: Int?;
var usrs_imss: String?;
var usrs_fecha_ingreso: String?;
var usrs_plantel_residencia: Int?;
var usrs_foja: String?;
var usrs_tomo: String?;
var usrs_licencia: String?;
var usrs_direccion: String?;
var usrs_reincorporacion: String?;
var usrs_stsu_id: Int?;
var usrs_tpsg_id: Int?;
var usrs_curp: String?;
var usrs_enc_password: String?;
}
that is the category and performance to get information from my webservice, the operate title is downloadData:
import Basis
import SwiftUI
class WebService {
func downloadData<T: Codable>(_ dynamicType: T.Sort,fromURL: String) async -> GenericResponse<JwtResponse>? {
do {
var urlComponents = URLComponents(string: fromURL)!
let queryItems = [URLQueryItem(name: "actividad", value: "AppLoginCode"),
URLQueryItem(name: "data", value: "{"email":"1","password":"pass_123"}")]
urlComponents.queryItems = queryItems
let url = urlComponents.url!
//guard let url = URL(string: fromURL)?.appending(queryItems: queryItems) else { throw NetworkError.badUrl }
let (information, response) = strive await URLSession.shared.information(from: url)
guard let response = response as? HTTPURLResponse else { throw NetworkError.badResponse }
guard response.statusCode >= 200 && response.statusCode < 300 else { throw NetworkError.badStatus }
if let base64Decoded = Knowledge(base64Encoded: information.base64EncodedString(), choices: Knowledge.Base64DecodingOptions(rawValue: 0))
.map({ String(information: $0, encoding: .utf8) }) {
// Convert again to a string
print("Decoded: (base64Decoded ?? "")")
}
guard let decodedResponse = strive? JSONDecoder().decode(GenericResponse<JwtResponse>.self, from: information) else { throw NetworkError.failedToDecodeResponse }
return decodedResponse
} catch NetworkError.badUrl {
print("There was an error creating the URL")
} catch NetworkError.badResponse {
print("Didn't get a legitimate response")
} catch NetworkError.badStatus {
print("Didn't get a 2xx standing code from the response")
} catch NetworkError.failedToDecodeResponse {
print("Didn't decode response into the given kind")
} catch {
print("An error occured downloading the information")
}
return nil
}
}
that is my Observable to name downloadData:
class PostViewModel: ObservableObject {
@Printed var postData: GenericResponse<JwtResponse> = GenericResponse()
func fetchData() async {
guard let downloadedPosts: GenericResponse<JwtResponse> = await WebService().downloadData(JwtResponse.self,fromURL: "https://***********************.com/BackEnd/WsBackEnd.php") else {return}
postData = downloadedPosts
}
}
as i remark, i decoded the webservice response after which i get the proper Json that i count on:
{
"response":"OK",
"message":null,
"information":{
"jwtEncode":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MjI3MjY5MzMsImlzcyI6ImxvY2FsaG9zdCIsIm5iZiI6MTcyMjcyNjkzMywiZXhwIjoxNzI1MzE4OTMzLCJlbWFpbCI6ImVkZXI0MTRjQGdtYWlsLmNvbSIsInVzZXJuYW1lIjoiZWFwMDMxIn0.qu_F2zQceWsMT0pDCugOo__aD8SE5bRZRsbS5haflP8",
"jwtDecode":{
"iat":1722726933,
"iss":"localhost",
"nbf":1722726933,
"exp":1725318933,
"e-mail":"[email protected]",
"username":"eap031"
},
"usuario":{
"usrs_id":"1",
"usrs_nombre":"Eder Alexis",
"usrs_numero_asoiciado":"1",
"usrs_telefono":"2147483647",
"usrs_sexo":"1",
"usrs_usuario":"eap031",
"usrs_correo":"[email protected]",
"usrs_plantel":"6"
}
}
}