HTTP请求正文中的传递数组

问题描述 投票:0回答:2

我想在我的请求中传递这样的数组:

{
"ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]
}

我确实喜欢那样,但是我不确定服务器是否按预期的方式获得:

    request.httpBody = try JSONSerialization.data(withJSONObject: ids, options: .prettyPrinted)
swift xcode
2个回答
0
投票

您应该为此目的使用Dictionary。方法如下:

let dictionary = ["ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]]
request.httpBody = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)

建议:现代方法是使用JSONEncder()。你可以用谷歌搜索,在线有很多解决方案。如果您仍在挣扎,可以在评论中询问方法,我很高兴您找出来。


0
投票

您可以使用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)
© www.soinside.com 2019 - 2024. All rights reserved.