Search code examples
iosodataswift4decodable

Issue with parsing @odata values using Swift


My service response is following:

{
"@odata.context" = "https://xxx-d.www.com/odata/$metadata#Members";
"@odata.count" = 1;
 value = ({
        email = "Suamasu@xxx.com";
        memberType = User;
        name = "Suse";
        title = "Manager";
   });
}

I am able to decode value which using Decodable swift type, however I need "@odata.count" value to be decoded from response.

struct Members: Decodable {
    let value: [Member]
}

struct Member: Decodable {
    let name: String?
    let email: String
    let memberType: String?
    let title: String?
}

Solution

  • Can you try to add coding keys to Members?

    struct Members: Decodable {
        let context: String
        let count: Int
        let value: [Member]
    
        enum CodingKeys: String, CodingKey {
            case context = "@odata.context"
            case count = "@odata.count"
            case value 
        }
    }
    

    More info: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types