我想以字典格式发送参数,同时选择或取消选择应该在字典中添加或删除元素



>嗨,我正在尝试将字典格式数组发送到 API 调用。但我没有任何想法要迅速发送。我的Android开发人员同事向我发送了他发送的以下代码。

for (int i = 0; i < CheckedName.size(); i++) {
JSONObject j = new JSONObject();
j.put("product", CheckedName.get(i));
j.put("quantity", CheckedQty.get(i));
jsonCategoryArray.put(j);

} finalObject.put("products", jsonCategoryArray(;

我想按以下格式发送

{“products”:[{“product”:“1711”,“quantity”:“2”},{“product”:“1713”,“quantity”:“1”},{“product”:“1718”,“quantity”:“3”},{“product”:“444”,“quantity”:“1”},{“product”:“6”,“quantity”:“1”},{“product”:“4914”,“quantity”:“1”},{“product”:“921”,“quantity”:“1”},{“product”:“11835”,“quantity”:“1”},{“product”:“11946”,“quantity”:“1”},{“product”:“12046”,“quantity”:“1”},{“product”:“12326”,“quantity”:“1”},{“product”:“12571”,“quantity”:“1”},{“product”:“273”,“quantity”:“1”},{“product”:“13410”,“quantity”:“1”},{“product”:“13435”,“quantity”:“1”},{“product”:“13665”,“quantity”:“1”},{“product”:“13795”,“quantity”:“1”},{“product”:“3553”,“quantity”:“1”}]}

我尝试在我的桌子代表上遵循方法,但我不确定这是否有效..任何人都能帮助我解决这个问题。

did选择方法

self.productDic["product"] = self.productIDString
self.productDic["quantity"] = self.productQtyString
self.productArray.append(self.productDic)

不知道如何从 didDeselect 方法中删除... 这给了我以下格式

Product Dictionary : [["product": "3004", "quantity": "1"], ["product": "1716", "quantity": "1"]]

之后,我必须按如下所示传递产品数组

param = ["products":self.productArray] as [String : AnyObject]
AF.request("(base_url)basket/mass/add/", method: .post, parameters: param, encoding: URLEncoding(), headers: headers).validate(statusCode: 200..<299).responseJSON { response in
print("sent param to selected shopping products (param)")

请帮助我一种比我的方法更简单的方法来实现这一点,或者帮助我从 didDeselect 方法中删除同一数组的值。我被困在这个上面。

根据API 请求的要求创建 JSON,就像。

{"products":[{"product":"1711","quantity":"2"},{"product":"1713","quantity":"1"}}

在didSelect方法中,只需在数组中添加选定的项目,或者您可以在模型中添加isSelected标志以检查用户选择的内容。

例如型号:

struct Product {
var product: Int
var quantity: Int
//Helper property
var isSelected: Bool = false
}

现在,在里面选择了方法:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
products[indexPath.row].isSelected = !products[indexPath.row].isSelected
}

最后,当您想点击API时,只需像这样过滤产品列表中的所有选定项目即可。

let selectedProducts = products.filter({$0.isSelected})

现在,创建 JSON:

extension Dictionary {
var jsonStringRepresentation: String? {
guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
options: [])      else {
return nil
}

return String(data: theJSONData, encoding: .ascii)
}
}
private func createJSON(from list: [Product]) -> String {
var productDic = [[String: String]]()
for item in list {
let param = ["product": "(item.product)", "quantity": "(item.quantity)"]
productDic.append(param)
}
let finalDictionary = ["products": productDic]
return finalDictionary.jsonStringRepresentation ?? ""
}
print(createJSON(from: products))

最新更新