gpt4 book ai didi

ios - 如何在 swift 中为 Post 请求创建 JSON Body

转载 作者:行者123 更新时间:2023-11-28 09:47:49 24 4
gpt4 key购买 nike

我必须使用以下 Json 主体发出请求。我很难在制作 json 主体时动态添加“房间”节点。

{
"from": "2019-05-06",
"to": "2019-05-07",
"destinationId": "DXB",
"destination": "Dubai - United Arab Emirates",
"roomsCount": 2,
"room1":{"age":[],"adult":2,"children":0},
"room2":{"age":[],"adult":2,"children":0}
}

最佳答案

尝试使用 Swift 4 的 Encodable创建 JSON。

例子:

struct Body: Encodable {
var from: String
var to: String
var rooms: [Room]

init(from: String, to: String, rooms: [Room]) {
self.from = from
self.to = to
self.rooms = rooms
}
}

struct Room: Encodable {
var age: Int
var adults: Int
var children: Int

init(age: Int, adults: Int, children: Int) {
self.age = age
self.adults = adults
self.children = children
}
}

let body = Body(from: "Amsterdam", to: "Dubai", rooms: [Room(age: 22, adults: 1, children: 0), Room(age: 54, adults: 0, children: 1)])
let encoded = try JSONEncoder().encode(body)
//String(data: encoded, encoding: .utf8)
//{"from": "Amsterdam", "to": "Dubai", "rooms": [{"age":22,"children":0,"adults":1},{"age":54,"children":1,"adults":0}]}

关于ios - 如何在 swift 中为 Post 请求创建 JSON Body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com