ios – How to use UUID as property name for Swift API data model


I’m currently using an API to get data for a iOS app using Swift.

I’m having an issue creating the data model because one of the property uses a UUID as its name.
Does anyone know a solution for this ?

Here is the API data in question :
The part I can’t get in a model is the part using the name “11a4a746-30bb-4dfd-980f-39c4dfd84412”.

{
    "profiles": {
        "11a4a746-30bb-4dfd-980f-39c4dfd84412": {
            "profile_id": "11a4a746-30bb-4dfd-980f-39c4dfd84412",
             ...
        }

...

}

Here is the data models I currently have :

struct Profiles: Codable {
    let profiles: ProfilesClass
}

struct ProfilesClass: Codable {
    let profile_id: The11A4A74630Bb4DFD980F39C4Dfd84412

    enum CodingKeys: String, CodingKey {
        case profile_id = "11a4a746-30bb-4dfd-980f-39c4dfd84412"
    }
}

enum SBError: Error {
    case invalidURL
    case invalidResponse
    case invalidData
    case dataCorrupted
    case keyNotFound
    case valueNotFound
    case typeMismatch
}

Here is the data fetching function

func fetchData() async throws -> Profiles {
        let endpoint = ENDPOINT URL GOES HERE IN ACTUAL CODE
        
        guard let url = URL(string: endpoint) else {
            throw SBError.invalidURL
        }
        
        let (data,response) = try await URLSession.shared.data(from: url)
        
        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            throw SBError.invalidResponse
        }
        
        do {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            return try decoder.decode(Profiles.self, from: data)
        } catch let DecodingError.dataCorrupted(context) {
            print(context)
            throw SBError.dataCorrupted
        } catch let DecodingError.keyNotFound(key, context) {
            print("Key '\(key)' not found:", context.debugDescription)
            print("codingPath:", context.codingPath)
            throw SBError.keyNotFound
        } catch let DecodingError.valueNotFound(value, context) {
            print("Value '\(value)' not found:", context.debugDescription)
            print("codingPath:", context.codingPath)
            throw SBError.valueNotFound
        } catch let DecodingError.typeMismatch(type, context)  {
            print("Type '\(type)' mismatch:", context.debugDescription)
            print("codingPath:", context.codingPath)
            throw SBError.typeMismatch
        } catch {
            print("error: ", error)
            throw SBError.invalidData
        }
    }

I tried using

enum CodingKeys: String, CodingKey {
        case profile_id = "11a4a746-30bb-4dfd-980f-39c4dfd84412"
    }

but this doesn’t seem to work. I still get a KeyNotFound error.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img