【发布时间】:2020-02-10 17:04:34
【问题描述】:
我正在尝试使用 JSONSerialization 通过 PUT 请求更新属性。 这是我的功能:
func updateRGPDStatus(user:UserModel){
let parameters = ["firstname": user.firsname as Any,
"lastname": user.lastname as Any,
"mail": user.mail as Any,
"has_web_access": user.has_web_access as Any,
"has_mobile_access": user.has_mobile_access as Any,
"id_user": user.id_user as Any,
"has_accepted_rgpd": user.rgpd as Any
] as [String : Any]
guard let url = URL(string: UPDATE_RGPD_STATUS) else { return }
var request = URLRequest(url: url)
request.httpMethod = "PUT"
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
catch {
print(error)
}
}
}.resume()
}
这是我应该更新的 json:
{
"user": {
"firstname": "first_name",
"lastname": "last_name",
"mail": "validEmail@mail.com",
"has_web_access": true,
"has_mobile_access": true,
"id_user": 17,
"has_accepted_rgpd": false
}
}
当我发送请求时,我收到了“缺少参数”类型的错误,因为我的请求中没有包含“用户”属性,在我学习的这个阶段我不知道该怎么做。请提供任何帮助。谢谢你^^
【问题讨论】:
标签: json swift xcode json-serialization