发布可编码对象

时间:2017-12-17 19:01:57

标签: api swift4

我有一个可编码的类:

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请求是错误还是什么?我不完全确定为什么我会收到此错误,其他人是否理解为什么?

1 个答案:

答案 0 :(得分:0)

您正在序列化结构两次 - JSONEncoder已完成工作 - 这不起作用

替换

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

request.httpBody = jsonData

忽略错误。处理它们!