如何在 swift 中为 Post 请求创建 JSON 正文
How to create JSON Body for Post request in swift
我必须使用以下 Json 正文提出请求。我很难在制作 json 主体时动态添加 "room" 节点。
{
"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}]}
我必须使用以下 Json 正文提出请求。我很难在制作 json 主体时动态添加 "room" 节点。
{
"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}]}