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

Weird error from JSONDecoder

Forums > 100 Days of SwiftUI

@ddko  

Currently working Friendface but I have this werid error

if use Response.self the error will be

failed The data couldn’t be read because it isn’t in the correct format.

but if i changed Response.self to [User].self

The data will be loaded without error

Related code down here:

The structs

 struct Response: Codable {
    var users: [User]
}

struct User : Codable {
    var id: String
    var isActive: Bool
    var name: String
    var age: Int
    var company: String
    var email: String
    var address: String
    var about: String
    var registered: String
    var tags: [String]
    var friends : [Friend]

    struct Friend: Codable {
        var id: String
        var name: String
    }
}
func loadData () async {
        guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else { print("Invalid URL")
            return
        }

        do {
            let ( data, _) = try await URLSession.shared.data(from: url)
            let decoded = try JSONDecoder().decode(Response.self, from: data) // to be replaced by [User].self
            print(decoded)
            users = decoded.users

        } catch let error {
            print("failed \(error.localizedDescription)")
        }

    }

2      

The JSON file that it calling has no key of users so it could not decode it, but does have an array of the User which is why it worked with [User].self

2      

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.