[英]Create a JSON parameter in Swift
I want to call a API with a post and give it parameters about the body.我想通过帖子调用 API 并为其提供有关正文的参数。 I need the parameter in following style.
我需要以下样式的参数。
"linked_users": [ "5dc73d6e1c20540b24336681", "5dca64f4bf98ec2ada3b315e"]
In Postman the json above is working, but if I create it I Swift, I get a bad request parsing error from the API.在 Postman 中,上面的 json 正在工作,但是如果我使用 Swift 创建它,我会收到来自 API 的错误请求解析错误。
var linkedUserString = ""
if let data = try? JSONSerialization.data(withJSONObject: stringArray, options: []){
if let json = String(data: data, encoding: String.Encoding.utf8)
{
linkedUserString = json
}
}
The value of linkedUserString is LinkedUserString 的值是
"[\"5dc73d6e1c20540b24336681\",\"5dca64f4bf98ec2ada3b315e\"]"
This String is converted with Codable to the final body value with the other parameters.此字符串使用 Codable 转换为带有其他参数的最终正文值。
- description : "location description"
▿ location : LocationCodable
- latitude : "0.0"
- longitude : "0.0"
- description : "Test Ort"
- linked_users : "[\"5dc73d6e1c20540b24336681\",\"5dca64f4bf98ec2ada3b315e\"]"
If I call the API without the linked_users parameter it works fine.如果我在没有linked_users 参数的情况下调用API,它工作正常。
Somebody knows what I am doing wrong?有人知道我做错了什么吗?
Make correct model:制作正确的模型:
struct Model: Codable {
var description: String!
var location: LocationCodable!
var linked_users: [String]!
}
and encode it, instead of encoding parameter linked_users
itself.并对其进行编码,而不是对参数
linked_users
本身进行编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.