Home > OS >  Nested Json data won't be decoded using Swift language?
Nested Json data won't be decoded using Swift language?

Time:10-26

I'm receiving response data from an API, when I'm trying to decode it by using json decoder, the nested json data won't be decoded because it returns null.

json data as follow:

{
    "token": "string",
    "details": {
        "ID": "string",
        "Name": "string",
        "Message": null
    }
}

Decoding model is:

struct response: Codable {
    let token: String?
    let usrData: userData?
}
struct userData:Codable{
    let ID,Name,Message: String?
}
URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                completion(.failure(.custom(errorMessage: "Please check internet connection")))
                return
            }
            guard let loginResponse = try? JSONDecoder().decode(response.self, from:data) else
            {
                completion(.failure(.invalidCredentials))
                return
            }
            print(loginResponse.userData?.userID as Any) //returns nil
            print(loginResponse.token) //token printed
            guard let token = loginResponse.token else {
                completion(.failure(.invalidCredentials))
                return
           }
            completion(.success(token))
        }.resume()

The token from the response will be successfully decoded, but the userData returns null.


CodePudding user response:

Your model's property name and decoded json property name must be equal if your are not mapping , so change your struct with :

struct response: Codable {
    let token: String?
    let details: userDto?
}

CodePudding user response:

That certainly can not work, first, in your response struct you have a let variable that says usrData that can not be identified as details. Second you write usrData: userDto what is userDto you clearly did a mistake or forgot to mention it. However, do it like that for example:

struct Response: Codable {
    let token: String?
    let details: UserData?
}

struct UserData: Codable {
    let ID,Name,Message: String?
}

let filePath = Bundle.main.path(forResource:"test", ofType: "json")
let data = try Data(contentsOf: URL(fileURLWithPath: filePath!))

if let loginResponse = try? JSONDecoder().decode(Response.self, from: data) {
    loginResponse
}

The example is not completely correct, because fileURLWithPath is deprecated but you should get the idea from it.

I also recommend following some basic roles, like writing Structs with an uppercase letter.

I hope I could help.

  • Related