我正在尝试使用 JSONEncoder 将四个不同的数组编码为 json 格式,但我无法转换数组。所以,请帮帮我。我正在为 iOS 11 使用 swift 4、xcode 9。
我的数组是:
var timeCart //dynamic data as string
var 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"
}
]
}