Xcode keeps giving me the error "Expected to decode Array<Any> but found a dictionary instead"

I want to print the information of the login user on the screen, but I fail

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath:
, debugDescription: "Expected to decode Array but found a
dictionary instead.", underlyingError: nil))

My current JSON model look like this:

{
    "ad": "Mobile API",
    "adres": "1",
    "aversiyon": 0,
    "changeby": 113,
    "changedate": "2022-06-10Z",
    "createdate": "2022-06-10Z",
    "dogumyili": "1930",
    "email": "mobileapi@asy.com",
    "gversiyon": 0,
    "ilce": "Beşiktaş",
    "klinikid": 0,
    "kullaniciid": 113,
    "kversiyon": 0,
    "phone": "(537) 226-6433",
    "profil": "Hasta Profili",
    "resifre": "TVsXh+6Uoiie4daIpI3ojw==",
    "rversiyon": 0,
    "sehir": "İstanbul",
    "sifre": "TVsXh+6Uoddsie4daIpI3ojw==",
    "soyad": "Test",
    "tcno": "",
    "ulke": "Türkiye"
}

Code:

struct MemberModel: Codable {
    let ad, adres: String
    let aversiyon, changeby: Int
    let changedate, createdate: String
    let dogumyili, email: String
    let gversiyon: Int
    let ilce: String
    let klinikid, kullaniciid, kversiyon: Int
    let phone, profil, resifre: String
    let rversiyon: Int
    let sehir, sifre, soyad: String
    let tcno: String?
    let ulke: String
}

func getAllMemberInformation(token: String, email: String, completion: @escaping (Result<[MemberModel], NetworkError>) -> Void){
        
        guard let url = URL(string: "http://ec2-3-74-42-117.eu-central-1.compute.amazonaws.com:8080/dentistodayapis/getkullanici") else {
            completion(.failure(.invalidURL))
            return
        }
        var request = URLRequest(url: url)
        request.addValue("\(token)", forHTTPHeaderField: "credentialtoken")
        request.addValue("\(email)", forHTTPHeaderField: "username")
        
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                completion(.failure(.noData))
                return
            }
            do{
                let informations = try JSONDecoder().decode([MemberModel].self, from: data)
                completion(.success(informations))
            } catch {
                print(String(data: data, encoding: .utf8) as Any)
            print(error)

            completion(.failure(.decodingError))
            print("\(email)")
            print("\(token)")
            }
        }.resume()
        
    }

class MemberViewModel: ObservableObject {
    
    @Published var members:[MemberVM] = []
    
    func getAllInformations(){
        let defaults = UserDefaults.standard
        guard let token = defaults.string(forKey: "jsonwebtoken") else {
            return
        }
        guard let email = defaults.string(forKey: "email") else {
            print("Haa")
            return
        }
        
        Webservice().getAllMemberInformation(token: token, email: email) { result in
            switch result {
                
            case .success(let members):
                DispatchQueue.main.async {
                    self.members = members.map(MemberVM.init)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}


struct MemberVM {
    let member: MemberModel
    
    let id = UUID()
    
    var ad: String {
        return member.ad
    }
    var soyad: String {
        return member.soyad
    }
    var email: String {
        return member.email
    }
    var phone: String {
        return member.phone
    }
    var dogumyili: String {
        return member.dogumyili
    }
    var ulke: String {
        return member.ulke
    }
    var sehir:String {
        return member.sehir
    }
    var ilce: String {
        return member.ilce
    }
    var adres: String {
        return member.adres 
    }
    var tcno: String {
        return member.tcno ?? "empty"
    }
    
}

View:

List(memberVM.members, id:\.id) { member in
                    VStack{
                        Text("\(member.ad)")
                        Spacer()
                        Text("\(member.soyad)")
                    }
                }

Xcode keeps giving me the error "Expected to decode Array but found a dictionary instead". I don't understand what it mean here. More precisely, I did not understand what to do. I used the same code to pull other information from JSON and it worked there. I looked at the answers to the questions asked under this title before, but I could not get an answer to my question. How can I fix this?

Take a looking at what you're decodeing there, what the error says, and think about the difference between arrays and objects.

1 Like

I suggest porting your JSON model to a struct, like this:

struct JSON: Decodable {
 // Contents here - use init() to customize data
}

This is saying to decode an array of MemberModels but perhaps you just want to decode a single member model instead? In other words:

let informations = try JSONDecoder().decode(MemberModel.self, from: data)
1 Like

Thank you @Ray_Fix