LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Weird error from JSONDecoder

Forums > 100 Days of SwiftUI


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: "") else { print("Invalid URL")

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

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



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


Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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.