我是新手,但是我一直试图弄清楚JSONDecoder如何处理需要从MySQL数据库中检索数据的登录功能,如下面的代码所示,并且正在接收这个错误。
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()
}
临时结构我一直试图使用:
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
}
}
JSON响应字符串显示为:
[{"U_ID":"1",
"Email":"test",
"Password":"test",
"UserType":"Teacher"}]
任何帮助都会受到大力赞赏。
答案 0 :(得分:18)
此处,JSON数据为Array
的{{1}}。
变化
Objects
到
try decoder.decode(User.self, from: data)
示例:强>
try decoder.decode(Array<User>.self, from: data)
注意:为了更好地理解,这是关于swift 4中JSON解析的video系列