Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift4 JSONDecoderExpected to decode Dictionary<String, Any> but found an array instead [duplicate]

Tags:

json

php

swift

I'm pretty newbie with this, but I've been attempting to work out how JSONDecoder works for a login function that needs to retrieve data from a MySQL database, as shown in my code below and am receiving this error.

Swift Code:

func testParseJson(){

                var request = URLRequest(url: URL(string: "https://test.php")!)
        request.httpMethod = "POST"

        let postString = ("Email=test&Password=test")
        print(postString)
        request.httpBody = postString.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else { return }
            do {
                var responseString = String(data: data, encoding: .utf8)!
                print("new response string \(responseString)")
                let decoder = JSONDecoder()
                let newData = try decoder.decode(User.self, from: data)
                print(newData.Email)
                print(newData.UserType)
            } catch let err {
                print("Err", err)
            }
            }.resume()
    }

Temporary Struct I have been attempting to use:

struct User: Decodable {
 let U_ID: String
 let Email: String
 let Password: String
 let UserType: String

private enum CodingKeys: String, CodingKey {
    case U_ID
    case Email
    case Password
    case UserType
 }
}

And the JSON response string reads:

[{"U_ID":"1",
"Email":"test",
"Password":"test",
"UserType":"Teacher"}]

Any help would be massively appreciated.

like image 251
A Bowl of Fruit Avatar asked Apr 08 '18 17:04

A Bowl of Fruit


1 Answers

Here, JSON data is Array of Objects.

change

try decoder.decode(User.self, from: data)

to

try decoder.decode(Array<User>.self, from: data)

Example:

var users = [User]()

let data = """
[{"U_ID":"1","Email":"test","Password":"test","UserType":"Teacher"}]
""".data(using: .utf8)

do{
    users = try JSONDecoder().decode(Array<User>.self, from: data!)
}catch{
    print(error.localizedDescription)
}

print(users.first?.Email)

Note: For better understanding, this is my video series about JSON parsing in swift 4

like image 113
Rajamohan S Avatar answered Oct 16 '22 01:10

Rajamohan S