【问题标题】:Swift used Codable, but the type is not correctSwift 使用了 Codable,但是类型不正确
【发布时间】:2020-10-05 02:54:57
【问题描述】:

我知道 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()
}

try decoder.decode

没有错误

但只在 urlRequest.httpBody = 试试? JSONEncoder().encode(login)有什么问题?

【问题讨论】:

  • 你想编码什么userId 和userPw?您需要编码login 的实例,而不是login 类型。
  • userId 和 userPw 只是 api 值。我正在尝试通过连接到服务器使用 POST 方法登录。
  • 我知道。但是您要发布什么值?显示要发送到服务器的 JSON。
  • 我只是想直接在IdTextField和PwTextField中输入值,并将输入值发送给服务器。
  • 这是一个很好的例子,为什么以小写字母开头的结构会引起混淆????

标签: swift codable jsondecoder jsonencoder


【解决方案1】:

你需要有这样的东西来设置值。

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)!)

【讨论】:

  • 谢谢。但是,当我在代码中将 Codable 更改为 Encodable 时,出现错误。 do { let decoder = JSONDecoder.init() let LoginList = try decoder.decode.. } add loginvalues 我只能将它用作 Codable 吗?那么就没有错误了。
  • 对不起,我不知道我为什么这样做。您可以将其保留为 Codable,它应该适合您。
猜你喜欢
  • 2019-03-11
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
相关资源
最近更新 更多