发布可编码对象

问题描述 投票:-1回答:1

我有一个可编码的类:

struct Authentication : Codable
{
   let grant_type : String = "password"
   let client_id : String = "6_46db26s9zag4s4w80gc08cso804go4goccg88kcwoso0og5goo"
   let username : String
   let password : String
}

我需要发布到RESTful API,所以我在按钮点击时调用此函数:

let url = URL(string: ApiUrl().GetUri(uri: ApiUri().LoginURL))
    var request = URLRequest(url: url!)
    let encoder = JSONEncoder()
    let jsonData = try! encoder.encode(Authentication(username: txtUsername.text!, password: txtPassword.text!))

    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject: jsonData, options: [])

    URLSession.shared.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in
        if let safeData = data{
            print("response: \(String(data:safeData, encoding:.utf8))")
        }
    }

但是出于某些原因,只要它出现在这种方法中我就会得到这个例外:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

我在POST请求中做错了什么?我不完全确定为什么我会收到此错误,其他人是否理解为什么?

api swift4
1个回答
0
投票

您正在对结构进行两次序列化 - JSONEncoder已经完成了这项工作 - 这是行不通的

更换

request.httpBody = try? JSONSerialization.data(withJSONObject: jsonData, options: [])

request.httpBody = jsonData

不要忽视错误。处理它们!

© www.soinside.com 2019 - 2024. All rights reserved.