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

SOLVED: JSON Decoding Error Using A Generic

Forums > Swift

I've come across a couple similar posts related to JSON decoding errors, but I think my problem is different enough to ask it:

Model

struct UserSLPForgotPasswordRequest: Codable {
    var email: String
}

struct UserSLPForgotPassword: Codable {
    let email: String
}

API Service Session/Encoding

URLSession.shared.dataTask(with: request) { (data, response, error) in

            if data != nil { print(data!) }

            if response != nil { print(response!) }

            if error != nil { print(response!) }

            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                completion(.failure(.custom(errorMessage: "Non-200 Response")))
//                print(response!)
                return
            }
            guard let data = data, error == nil else {
                completion(.failure(.custom(errorMessage: "No Data")))
                return
            }
            self.decode(data: data, completion: completion)

        }.resume()

Generic Decoder

    private func decode<T: Decodable>(data: Data, completion: @escaping (Result<T, AuthenticationError>) -> Void) {
        do {
            let jsonDecoded = try JSONDecoder().decode(T.self, from: data)
            completion(.success(jsonDecoded))
        } catch (let error) {
            print(error)
            completion(.failure(.decodingError))
        }
    }

Somewhere inside the decoder function I recieve this error:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

My back-end is working fine and sending me a 200 response, but I'm just not sure where the decoder is having its problems with the JSON.

I have only used the decoder with GET and POST requests that have multiple fields involved and this particular endpoint only receives a single field and technically isn't returning anything, so maybe it's something to do with that? IDK...

3      

Please post a sample of the JSON response. There is something in there the decoder doesn't like, right at the very beginning.

4      

Hey @roosterboy, you're right. The decoder is the problem, in that it's completely unneccessary :-)

I figured it out a bit later and the problem is I wasn't familiar with using Void() in place of the Decoders work for this particular endpoint; since it doesn't return any JSON, only a server response code.

So instead of

self.decode(data: data, completion: completion)

I just used

completion(.success(Void()))

And instead of being

Sad

I'm now

Glad

3      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn 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.