php – Swift4 JSONDecoderExpected解码Dictionary但找到了一个数组而不是[复制]

前端之家收集整理的这篇文章主要介绍了php – Swift4 JSONDecoderExpected解码Dictionary但找到了一个数组而不是[复制]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Swift JSONDecoder typeMismatch error2个
我对此很新手,但我一直试图弄清楚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数据是对象数组.

更改

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解析

猜你在找的PHP相关文章