我正在尝试使用JSONEncoder将四个不同的数组编码为json格式,但无法转换这些数组。所以,请帮帮我。我正在使用Swift 4,iOS 11的xcode 9。我的数组是:var timeCart //dynamic data as stringvar nameCart //dynamic data as string, ex. ["myNameOne", "myNameTwo", ...]var quantityCart //dynamic data as Int, ex. [2, 3, 5, ...]var priceCart //dynamic data as Int, ex. [82, 73, 65, ...]我的结构是:struct OrderDetailJSON: Encodable { let allOrder: [AllOrder] let TaxDetials: TaxDetail struct AllOrder: Encodable { let date_time: String let item: String let name: String let price: String } struct TaxDetail: Encodable { let tax_per: String let tax_name: String }}我正在尝试在表视图中这样编码let orderDetailsJSON = OrderDetailJSON(allOrder: [.init(date_time: "\(quantityCart[indexPath.row])", item: "\(quantityCart[indexPath.row])", name: "\(nameCart[indexPath.row])", price: "\(priceCart[indexPath.row])")], TaxDetials: .init(tax_per: defaults.string(forKey: "STORE_TAX")!, tax_name: defaults.string(forKey: "STORE_TAX_NAME")!)) do { let jsonData = try JSONEncoder().encode(orderDetailsJSON) let jsonString = String(data: jsonData, encoding: .utf8) print("order_details :" + jsonString!) }catch{ }我得到的输出是:order_details: { "TaxDetials": { "tax_per": "5", "tax_name": "CGST & SGST" }, "allOrder": [ { "date_time": "2", "name": "Manchurian", "item": "2", "price": "87" } ]}order_details: { "TaxDetials": { "tax_per": "5", "tax_name": "CGST & SGST" }, "allOrder": [ { "date_time": "3", "name": "Paneer Tikka", "item": "3", "price": "150" } ]}order_details: { "TaxDetials": { "tax_per": "5", "tax_name": "CGST & SGST" }, "allOrder": [ { "date_time": "2", "name": "snacks", "item": "2", "price": "54" } ]}我期望的输出是:order_details: { "TaxDetials": { "tax_per": "5", "tax_name": "CGST & SGST" }, "allOrder": [ { "date_time": "2", "name": "Manchurian", "item": "2", "price": "87" }, { "date_time": "3", "name": "Paneer Tikka", "item": "3", "price": "150" }, { "date_time": "2", "name": "snacks", "item": "2", "price": "54" } ]} 最佳答案 您的struct声明没有任何问题(除了您应该遵循Swift命名约定这一事实之外,对于变量名,它是lowerCamelCase-taxPer而不是tax_per,等等,并且您的属性名不使用正确的复数/单数形式)。问题在于,您正在为每个表视图单元格定义一个OrderDetailJSON实例,而对于表中的所有单元格,您的TaxDetails应该都相同,并且您实际上想创建一个OrderDetailJSON实例,该实例的数组属性为每个表视图单元格包含一个allOrder实例。您需要将AllOrder属性更改为mutable才能起作用。class YourTableViewController: UITableViewController { var orderDetails: OrderDetailJSON ... // You might need to use a different tableView function depending on your exact needs func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { orderDetails.allOrder[indexPath.row] = AllOrder(date_time: "\(quantityCart[indexPath.row])", item: "\(quantityCart[indexPath.row])", name: "\(nameCart[indexPath.row])", price: "\(priceCart[indexPath.row])") }}您需要确保使用正确的allOrder初始化orderDetails,并为TaxDetails预分配与要具有的所有表视图单元格相同数量的元素。一旦所有单元格都填满了信息,您只需要将allOrder转换为JSON,就无需逐个单元格地进行操作。 09-27 12:23