微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift使用了Codable,但是类型不正确

如何解决Swift使用了Codable,但是类型不正确

我知道Codable = Decodable&encodable,但是当从xcode调用json时,

Codable被作为结构给出,但错误提示

Argument type'login.Type' does not conform to expected type'encodable'出现。

json代码

struct login: Codable {
    var userId: String?
    var userPw: String?
class func LoginBoard(_ completeHandler: @escaping (login) -> Void) {
            
    let loginboard: String = MAIN_URL + "/member/login"
    guard let url = URL(string: loginboard) else {
      print("Error: cannot create URL")
        return
    }
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"
    urlRequest.addValue("application/json",forHTTPHeaderField: "Content-Type")
    urlRequest.addValue("application/json",forHTTPHeaderField: "Accept")
    urlRequest.httpBody = try? JSONEncoder().encode(login) // ERROR [Argument type 'login.Type' does not conform to expected type 'encodable']
            
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data,response,error) in
        guard error == nil else {
        print("error calling Post on /todos/1")
         print(error!)
           return
        }

        guard let responseData = data else {
        print("Error: did not receive data")
          return
        }

        do {
            let decoder = JSONDecoder.init()
            let LoginList = try decoder.decode(login.self,from: responseData)
            completeHandler(LoginList)
        }
        catch {
            print("error trying to convert data to JSON")
            return
        }
    }
    task.resume()
}

尝试解码器。解码

没有错误

但仅在 urlRequest.httpBody =中尝试? JSONEncoder()。encode(登录是什么问题?

解决方法

您需要使用类似的方法来设置值。

let loginvalues = login(userId: "john",userPw: "adfadfa")

urlRequest.httpBody = try? JSONEncoder().encode(loginvalues)

如果将其放置在游乐场内并运行它,您会看到获得json数据。

struct Login: Codable {
    var userId: String?
    var userPw: String?
}

let loginvalues = Login(userId: "john",userPw: "adfadfa")

let test = try? JSONEncoder().encode(loginvalues)
print(String(data: test!,encoding: .utf8)!)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。