Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.


>Solution :

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?
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading