Alwaysblue
Alwaysblue

Reputation: 11860

How to create an api response object type

I am doing an api call and getting a response back.

Suppose, the response is something like this

{
 data: {
 name: 'Varun', 
 id: 'szjsns3d', 
 email: '[email protected]'
 }
}

and this is my swift code

guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let createMeetingData = data else {
                return
}

do{
                let createMeetingResponse = try JSONSerialization.jsonObject(with: createMeetingData, options: []) as? [String : AnyObject]

I thought by doing [String : AnyObject], I will be able to do something like this

print(createMeetingResponse.data.id);

but this throws an error

Value of type '[String : AnyObject]?' has no member 'data'

Then I thought about creating a type for it (coming from a typescript background) but I wasn't able to find a way for doing it.

The answers which I was able to get involved using codeable for api request. (Encoding and decoding using codeable).

Can someone please help me in figuring out how I can achieve this without using codeable?

Update

I tried using decodable but it keeps giving me error

Type 'CreateMeetingResponse' does not conform to protocol 'Decodable

This is how I made decodable

struct  MeetingResponse {
    let id: String
    let name: String
    let email: String

}

struct CreateMeetingResponse:Decodable {
    let data:MeetingResponse
}

Upvotes: 0

Views: 499

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100533

You need

if let res = createMeetingResponse["data"] as? [String:Any] {
     if let id = res["id"] as? String {
         print(id)
     }
}

But it's better using Codable

do {
    let res = try JSONDecoder().decode(Root.self, from: createMeetingData)
    print(res.data.id)
}
catch {
    print(error)
}

struct Root: Codable {
    let data: DataClass
}


struct DataClass: Codable {
    let name, id, email: String
}

Upvotes: 1

Related Questions