John
John

Reputation: 1015

Keep getting the error “Expected to decode Array<Any> but found a dictionary | Swift

I have the following JSON that is formatted like this:

{
    "error":false
}

I understand that is not an array because it does not include square brackets on both sides, but I cannot seem to understand how to properly get Swift to interpret this correctly.

This is the structure I am using:

struct CheckStruct: Decodable {
    let error: String?
}

And the following is the function that should read the JSON:

private func JSONFunc() {
    guard let url = URL(string: "https://example.com/example/example.php"),
        let value = name.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "number=\(number)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, _, error in
        guard let data = data else { return }

        do {
            self.CheckRecord = try JSONDecoder().decode(Array<CheckStruct>.self,from:data)
            DispatchQueue.main.async {
                // Do something
            }
        }
        catch {
            print(error)
        }

        }.resume()
}

UPDATE: If I were to use the results of the function to create an if else statement, how would this look?

For example if results are true do this..

else do this...

Upvotes: 0

Views: 65

Answers (1)

emrcftci
emrcftci

Reputation: 3516

Your model should be like this:

struct CheckStruct: Codable {
    let error: Bool?
}

And your function should be like this:

private func JSONFunc() {
    guard let url = URL(string: "https://example.com/example/example.php"),
        let value = name.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "number=\(number)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else { return }

        do {
            let myData= try JSONDecoder().decode(CheckStruct.self, from:data)

             print(myData.error)
        } catch {
            print(error)
        }

    }.resume()
}

BONUS

//Create Typealias

typealias BoolHandler = ((Bool?) -> Void)

//Create Function with Completion

private func fetchData(_ completion: @escaping BoolHandler) {
    guard let url = URL(string: "https://example.com/example/example.php"),
        let value = name.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "number=\(number)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else { return }


        do {
            let myData= try JSONDecoder().decode(CheckStruct.self, from:data)

            DispatchQueue.main.async {
              completion(myData.error)
            }
        } catch {
            DispatchQueue.main.async {
              completion(nil)
            }
        }

    }.resume()
}

//Call Method

fetchData { isSuccess in

    if isSuccess {
        // Do something
    } else {
        // Do something
    }
}

I hope it will work for you.

Enjoy.

Upvotes: 1

Related Questions