Search code examples
iosswiftstructalamofire

How can I get decoded data from a struct inside a struct from an API


I am trying to learn how to use AlamoFire and I want to get the values of structures inside this struct MyData. How to achieve this ?


import Foundation
import Alamofire

struct MyData : Codable {
    
    let id: Int
    let uid : String
    let password : String
    let first_name : String
    let last_name :String
    let username : String
    let email : String
    let avatar : String
    let gender : String
    let phone_number : String
    let social_insurance_number : String
    let date_of_birth : String
    
    struct employment : Codable {
        let title : String
        let key_skill : String
    }
    
    struct address : Codable {
        var city : String
        var street_name : String
        var street_address : String
        var zip_code : String
        var state : String
        var country : String
        
        struct coordinates : Codable {
            var lat : Int
            var lng : Int
        }
    }
    
    
    struct credit_card : Codable{
        let cc_number : String
    }
    struct subscription : Codable {
        var plan : String
        var status : String
        var payment_method : String
        var term : String
    }
    
}


func getApi() {
   
    let url = "https://random-data-api.com/api/v2/users"
    AF.request(url).responseData { response in
        debugPrint(response)
        guard let data = response.data
        else{
           return
        }
        
        do {
            let decoder = JSONDecoder()
            let json = try decoder.decode(MyData?.self, from: data)
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            print("SOCIAL INSURANCE NUMBER : \(String(describing: json!.social_insurance_number))")  
        }
        catch{
            print(error)
        }   
    } 
  }

I tried to get data from an API. My data model had a structure inside a structure. I couldn't get the structures inside the parent structure but I could get the values of variables declared in the parent structure.


Solution

  • Insert following codes in your MyData to continue decoding.

        let employment: Employment
        let address: Address
        let credit_card: CreditCard
        let subscription: Subscription
    

    Don't forget to capitalize first letter on your structs, add var coordinates and change Int to Double.

    struct Employment: Codable {
        // ...
    }
    
    struct Address: Codable {
        // ...
        var coordinates: Coordinates // Add this
        
        struct Coordinates: Codable {
            var lat: Double // Change Int to Double
            var lng: Double // Change Int to Double
        }
    }
    
    struct CreditCard: Codable {
        // ...
    }
    
    struct Subscription: Codable {
        // ...
    }