TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How can I debug JSONDecoder?

Forums > Swift

I have added a new JSON format to my app but cannot get it to decode for some unknown reason.

I can get other formats to decode without problem so I think the problem is either my model has an error or my document has bad data.

Can anyone give me some clues how best to debug the decode to try and get some pointer to why it's failing?

Here's the fragment:

     if     let decodedResponse = try? JSONDecoder().decode(TS4300Inventory.self, from: data2) {
            print("After decode")
            results = decodedResponse.drives
            print(results)

        }

The "After decode" never appears so it's failing in the decode.

It's receiving the input successfully.

Thanks!

   

hi,

this might be a little more helpful ... it's a variation of related generic code that Paul has used in some videos, given that you have a Data in hand.

    func decode<T: Decodable>(from data: Data, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .iso8601) -> T {

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStrategy

        do {
            return try decoder.decode(T.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {
            fatalError("Failed to decode due to missing key '\(key.stringValue)' not found – \(context.debugDescription)")
        } catch DecodingError.typeMismatch(let type, let context) {
            fatalError("Failed to decode due to type mismatch '\(type)' – \(context.codingPath) - \(context.debugDescription)")
        } catch DecodingError.valueNotFound(let type, let context) {
            fatalError("Failed to decode due to missing \(type) value – \(context.debugDescription)")
        } catch DecodingError.dataCorrupted(_) {
            fatalError("Failed to decode because it appears to be invalid JSON")
        } catch {
            fatalError("Failed to decode: \(error.localizedDescription)")
        }
    }

you'd call this in the form

let decodedResponse: TS4300Inventory = decode(from: data2)

if the use of fatalError is not something that you want, you could easily turn this into a throwing function and handle the throw at the call site with the syntax shown above to handle all the catch cases.

hope that helps,

DMG

   

Convert data2 to a string for debugging purposes and check that it contains what you expect. The following Hacking with Swift article shows you how to convert a Data object to a string:

https://www.hackingwithswift.com/example-code/language/how-to-convert-data-to-a-string

The site quicktype.io lets you convert JSON into multiple programming languages, including Swift. You could compare your model to what quicktype generates and see what's different.

Showing the code for your model and showing the JSON you are getting would help people on this forum solve your problem.

   

Many thanks for the helpful replies!

DMG - it threw up a missing key so that has given me a starting point to fix.

SwiftDevJournal - had already done the data -> string to ensure I was feeding in what I was expecting. The quicktype.io tip is definitely of interest to help me validate my model (more precisely three models because the top level actually consists of two object arrays).

Again, my thanks - most appreciated!

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.