我想在我的请求中传递这样的数组:
{
"ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]
}
我确实喜欢那样,但是我不确定服务器是否按预期的方式获得:
request.httpBody = try JSONSerialization.data(withJSONObject: ids, options: .prettyPrinted)
您应该为此目的使用Dictionary
。方法如下:
let dictionary = ["ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]]
request.httpBody = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
建议:现代方法是使用JSONEncder()
。你可以用谷歌搜索,在线有很多解决方案。如果您仍在挣扎,可以在评论中询问方法,我很高兴您找出来。
您可以使用JSONEncoder
进行编码;
let yourList = ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]
struct DataModel: Encodable {
var ids: [String]
}
let data = DataModel(ids: yourList)
let encodedData = try! JSONEncoder().encode(data)
// JSON string value
let jsonString = String(data: encodedData, encoding: .utf8)