Alamofire在发送请求时拆分嵌套对象

时间:2019-08-06 07:50:47

标签: ios swift

我正在服务器上发送关注数据

params =  ["product": [["product_id": 1, "quantity": 6], ["product_id": 3, "quantity": 7], ["product_id": 4, "quantity": 1]]]
Alamofire.request("http://localhost/info-c.php", method:.post, parameters: params , headers:  getHeaderForLoggInUser() ).responseJSON { response in
                DispatchQueue.main.async(execute: {() -> Void in
                    switch response.result {
                    case .success:
                        if let json = JSON(response.result.value ?? [:]).dictionary{
                            print(json)
                            completed(json)
                        }else{
                            dError( "Internal server Error")
                        }
                        break
                    case .failure(let er):
                        dError( "Internal server Error \(er)")
                        break
                    }
                })
            }

但是在服务器端,我的身份是:

["product": [
  {
    "product_id" : "1"
  },
  {
    "quantity" : "6"
  },
  {
    "product_id" : "3"
  },
  {
    "quantity" : "7"
  },
  {
    "product_id" : "4"
  },
  {
    "quantity" : "1"
  }
]]

我也尝试过

encoding: JSONEncoding.default,

然后我得到

["{\"product\":": {
  "{\"product_id\":1,\"quantity\":6},{\"quantity\":7,\"product_id\":3},{\"product_id\":4,\"quantity\":1}" : ""
}]

我的API所需的输入格式如下:
产品[0] [产品ID]:1
产品[0] [数量]:6
产品[1] [产品ID]:2
产品[1] [数量]:6

Postman example

2 个答案:

答案 0 :(得分:2)

  1. 创建模型

    struct Product {
        var product_id: Int
       var quantity : Int
    }
    
  2. 从应用中填充模型-基于选择

    let product = Product.init(product_id: 1, quantity: 6)
    let product1 = Product.init(product_id: 2, quantity: 3)
    let product2 = Product.init(product_id: 4, quantity: 1)
    
    arrayProducts.append(product)
    arrayProducts.append(product1)
    arrayProducts.append(product2)
    
  3. 在调用服务器之前-根据服务器要求设置参数。

        var parameters = [String: Any]()
    
        for (index, element) in arrayProducts.enumerated() {
            let dynamicProductIDKey = "product[\(index)][product_id]"
            let dynamicProductIDValue = element.product_id
    
            let dynamicProductQuantityKey = "product[\(index)][quantity]"
            let dynamicProductQuantityValue = element.quantity
    
            parameters[dynamicProductIDKey] = dynamicProductIDValue
            parameters[dynamicProductQuantityKey] = dynamicProductQuantityValue
    
        }
    

现在您可以将参数共享给服务器。

谢谢

答案 1 :(得分:1)

尝试以下字典

let dict = [
    "product[0][product_id]" : "1",
    "product[0][quantity]" : "6",
    "product[1][product_id]" : "2",
    "product[1][quantity]" : "6",
]