12

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.

A Bowl of Fruit
  • 145
  • 1
  • 1
  • 6

1 Answers1

43

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

Rajamohan S
  • 7,229
  • 5
  • 36
  • 54
  • 2
    That worked brilliantly. As another noob question as I'm very new to swift, how might I access the users.first?.Email from somewhere else within the application? Its a login but it will need to use the email again later on. Thanks very much – A Bowl of Fruit Apr 08 '18 at 18:33
  • You can use `UserDefaults` to save this kinda data. So, you can get it anywhere and anytime until the app uninstall or Offload or until the value delete(logout). – Rajamohan S Apr 08 '18 at 18:36
  • @ABowlofFruit, see here : https://stackoverflow.com/questions/31203241/how-to-use-userdefaults-in-swift/31203348 – Rajamohan S Apr 08 '18 at 18:38
  • 1
    perfect answer. Thank you @RajamohanS – amp.dev Jul 07 '20 at 06:19
  • 1
    @amp.dev, You are welcome :D – Rajamohan S Jul 08 '20 at 07:21
  • also works if you replace `Array.self` with `[User].self` which is a little more idiomatic. – Logachu Nov 05 '21 at 17:19