1

I want to post json. here is what my parameters look like:

let parameterDictionary = [
    "customer_name": "John Doe",
    "customer_phone": "1234567890",
    "customer_address": "Velit incidunt odit atque quaerat ipsa.",
    "note": "Sequi quisquam ab ea et",
    "datetime_requested": "2020-06-19 09:04:25",
    "products": [
        [
            "id": 53,
            "amount": 15
        ],
        [
            "id": 63,
            "amount": 12
        ]
        
        ]] as [String : Any]

I can post with no problem. But the parameter is hardcoded. I have an Items struct that holds id and amount.

struct Items {
    var id: Int
    var amount: Int
}

and let's say i have items like this:

 let items = [Items(id: 53, amount: 12), Items(id: 64, amount: 29)]

How can I implement this in my parameterDictionary.?



In case you need how I handle posting:

    let Url = String(format: "https://example.com/api/v1/order")
    guard let serviceUrl = URL(string: Url) else { return }

    var items = [Items(id: 53, amount: 12), Items(id: 64, amount: 29)]
    
    let parameterDictionary = [
    "customer_name": "Didar J",
    "customer_phone": "1234567890",
    "customer_address": "Velit incidunt odit atque quaerat ipsa.",
    "note": "Sequi quisquam ab ea et",
    "datetime_requested": "2020-06-19 09:04:25",
    "products": [
        [
            "id": 53,
            "amount": 15
        ],
        [
            "id": 63,
            "amount": 12
        ]
        
        ]] as [String : Any]
    
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
        return
    }
    request.httpBody = httpBody
    
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
                
            } catch {
                print(error)
            }
        }
        }.resume()
hummaan
  • 113
  • 1
  • 5

2 Answers2

2

For only a few struct members I recommend a computed property to map the instance to a dictionary

struct Item {
    var id: Int
    var amount: Int
    
    var dictionaryRepresentation : [String:Int] { return ["id":id, "amount":amount] }
} 

let items = [Item(id: 53, amount: 12), Item(id: 64, amount: 29)]
let itemArray = items.map{$0.dictionaryRepresentation}

let parameterDictionary = [
"customer_name": "Didar J",
"customer_phone": "1234567890",
"customer_address": "Velit incidunt odit atque quaerat ipsa.",
"note": "Sequi quisquam ab ea et",
"datetime_requested": "2020-06-19 09:04:25",
"products": itemArray] as [String : Any]
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Use Codable models.

struct Customer: Encodable {
    let customerName, datetimeRequested, customerPhone, note, customerAddress: String
    let products: [Product]
}

struct Product: Encodable { // or conform existing `Items` model to Enodable
    let id, amount: Int
}

Then construct the model with initializers and set the httpBody as follows:

do {
    let encoder = JSONEncoder()
    encoder.keyEncodingStrategy = .convertToSnakeCase
    request.httpBody = try encoder.encode(customer)
} catch {
    print(error)
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47