0

I have to make a request by using the following Json Body. It is difficult for me to add "room" nodes dynamically while making json body.

{
  "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}
}
  • You can continue adding keys like dictionary["room\(index)"] = Room("age":[],"adult":2,"children":0) or change you json structure to "rooms":[{"age":[],"adult":2,"children":0},{"age":[],"adult":2,"children":0}] – roy May 06 '19 at 08:49
  • thanks , its better to change json structure – I Book Holiday May 06 '19 at 09:18

1 Answers1

6

Try using Swift 4's Encodable to create JSON.

Example:

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}]}
milo
  • 936
  • 7
  • 18