UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to decode JSON response with different type

Forums > Swift

Hello HWS Forum

I am using an API with have different JSON response type. for example of success, the response is :

{
    "status": "success",
    "result": {
        "useruuid": "ab872795-ee32-11eb",
        "usertoken": "DbXapngqtEynm6EKja3"
    }
}

in case of error, the response is like :

{
    "status": "error",
    "result": "token mismatch"
}

the task code handling the request have a ResponseType. the code is:

class func taskForPOSTRequest<ResponseType: Decodable>(url: URL, responseType: ResponseType.Type, body: String, completion: @escaping (ResponseType?, Error?) -> Void) {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = body.data(using: .utf8)
        //request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else {
                DispatchQueue.main.async {
                    completion(nil, error)
                }
                return
            }
            let decoder = JSONDecoder()
            do {
                let responseObject = try decoder.decode(ResponseType.self, from: data)
                DispatchQueue.main.async {
                    completion(responseObject, nil)
                }
            } catch {
                DispatchQueue.main.async {
                    completion(nil, error)
                }
            }
        }
        task.resume()
    }

How can I handle both response cases of the result node.

Thanks

2      

Here's one way you can do it:

struct User: Decodable {
    let userUUID: UUID
    let userToken: String

    enum CodingKeys: String, CodingKey {
        case userUUID = "useruuid"
        case userToken = "usertoken"
    }
}

enum ResponseType: Decodable {
    case user(User)
    case error(String)

    enum CodingKeys: String, CodingKey {
        case status
        case result
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let status = try container.decode(String.self, forKey: .status)

        switch status {
        case "success":
            let user = try container.decode(User.self, forKey: .result)
            self = .user(user)
        case "error":
            let errorString = try container.decode(String.self, forKey: .result)
            self = .error(errorString)
        default:
            fatalError("We got a weird case")
        }
    }
}

You would then switch over the value of the ResponseType parameter to the completion handler:

switch response {
case .user(let user):
    //you've got a User object here
case .error(let error):
    //you've got an error string here
}

5      

brilliant answer.

thank you so much. it work like a charm.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.