Php Swift4 JSONDECODEREX有望解码字典<;字符串,任意>;但是找到了一个数组
我对这方面非常熟悉,但我一直在尝试了解JSONDecoder如何用于需要从MySQL数据库检索数据的登录函数,如下面的代码所示,我收到了这个错误 Swift代码:Php Swift4 JSONDECODEREX有望解码字典<;字符串,任意>;但是找到了一个数组,php,json,swift,Php,Json,Swift,我对这方面非常熟悉,但我一直在尝试了解JSONDecoder如何用于需要从MySQL数据库检索数据的登录函数,如下面的代码所示,我收到了这个错误 Swift代码: func testParseJson(){ var request = URLRequest(url: URL(string: "https://test.php")!) request.httpMethod = "POST" let postString = ("E
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"}]
非常感谢您的帮助。这里,JSON数据是
对象的数组
改变
try decoder.decode(User.self, from: data)
到
尝试解码器。解码(Array.self,from:data)
示例:
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)
var users=[User]()
让数据为“”
[{“U_ID”:“1”,“Email”:“test”,“Password”:“test”,“UserType”:“Teacher”}]
“”数据(使用:.utf8)
做{
users=尝试JSONDecoder().decode(Array.self,from:data!)
}抓住{
打印(错误。本地化描述)
}
打印(用户。首次?。电子邮件)
注意:为了更好地理解,这是我关于swift 4中JSON解析的系列文章,非常出色。作为另一个noob问题,因为我对swift非常陌生,我如何访问用户。首先?从应用程序中的其他地方发送电子邮件?这是一个登录,但稍后需要再次使用电子邮件。非常感谢您可以使用UserDefaults
保存此类数据。因此,你可以随时随地获得它,直到应用卸载或卸载,或者直到值删除(注销)。@abowlofruit,请参阅此处:完美答案。多谢各位@RajamohanS@amp.dev,不客气
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)