参见英文答案 >
Swift JSONDecoder typeMismatch error2个
我对此很新手,但我一直试图弄清楚JSONDecoder如何为需要从MysqL数据库检索数据的登录功能起作用,如下面的代码所示,并且收到此错误.
我对此很新手,但我一直试图弄清楚JSONDecoder如何为需要从MysqL数据库检索数据的登录功能起作用,如下面的代码所示,并且收到此错误.
SWIFT代码:
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数据是对象数组.
原文链接:https://www.f2er.com/php/130867.html更改
try decoder.decode(User.self,from: data)
至
try decoder.decode(Array<User>.self,from: data)
例:
var users = [User]() let data = """ [{"U_ID":"1","UserType":"Teacher"}] """.data(using: .utf8) do{ users = try JSONDecoder().decode(Array<User>.self,from: data!) }catch{ print(error.localizedDescription) } print(users.first?.Email)
注意:为了更好地理解,这是我在video系列中关于swift 4中的JSON解析