Swift4 JSONDecoder预计解码Dictionary <string,any =“”>但是找到了一个数组

时间:2018-04-08 17:57:00

标签: php json swift

我是新手,但是我一直试图弄清楚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"}]

任何帮助都会受到大力赞赏。

1 个答案:

答案 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系列