将复杂的 json 发布到 api

Posting complex json to api

我要postjson。这是我的参数:

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]

我 post 没问题。但是参数是硬编码的。我有一个 Items 结构,其中包含 idamount.

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

假设我有这样的物品:

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

如何在我的 parameterDictionary 中实现它?



如果你需要我如何处理 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()

使用 Codable 个模型。

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
}

然后构造带有初始值设定项的模型并设置httpBody如下:

do {
    let encoder = JSONEncoder()
    encoder.keyEncodingStrategy = .convertToSnakeCase
    request.httpBody = try encoder.encode(customer)
} catch {
    print(error)
}

对于少数结构成员,我推荐计算 属性 将实例映射到字典

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{[=10=].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]