WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

1      

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

2      

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

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.