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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With