如何快速创建JSON主体用于发布请求

时间:2019-05-06 08:37:04

标签: ios json swift post urlrequest

我必须使用以下Json Body进行请求。我很难在制作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}
}

1 个答案:

答案 0 :(得分:5)

尝试使用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}]}