我有一個嵌套結構:
struct Order: Codable {
let foodList: [FoodList]
let name: String
let phone: String
let email: String
}
struct FoodList: Codable {
let foodName: String
let foodID: String
let foodAmount: Int
}
我需要從這個結構中制作 JSON。它必須是這樣的:
{
"name": "Name",
"phone": " 1 999 999 999 999",
"email": "[email protected]",
"foodList": [
{
"foodName": "Big Mac",
"foodID": "115",
"foodAmount": 2
},
{
"foodName": "Naggets",
"foodID": "221",
"foodAmount": 5
}
]
}
但我總是得到這個 JSON)
[
{
"email": "Name",
"phone": " 1 999 999 999 999",
"foodList": {
"foodAmount": 2,
"foodID": "115",
"foodName": "Big Mac"
},
"name": "[email protected]"
},
{
"email": "[email protected]",
"phone": " 1 999 999 999 999",
"foodList": {
"foodAmount": 5,
"foodID": "221",
"foodName": "Naggets"
},
"name": "Name"
}
]
在 JSON 中,它必須是 1 個人和一組選定的食物。
我用這個代碼撰寫 JSON 來構造:
let orderList = [OrderList]()
for index in 0..<subMenuList.count {
if subMenuList[index].foodList.foodSelectedAmount != 0 {
orderList.append(OrderList(
foodList: FoodListOrder(
foodName: subMenuList[index].foodList.foodName,
foodID: subMenuList[index].foodList.foodID,
foodAmount: subMenuList[index].foodList.foodSelectedAmount),
name: mainView.nameTextField.text!,
phone: mainView.phoneTextField.text!,
email: mainView.emailTextField.text!))
}
let jsonEncoder = JSONEncoder()
do {
let jsonData = try jsonEncoder.encode(orderList)
print(String(data: jsonData, encoding: .utf8)!)
} catch {
print(error)
}
“FOR”塊和文本欄位出了點問題……我想。每次回圈時,我都會從文本欄位中附加人員資料。
uj5u.com熱心網友回復:
假設Order等于OrderList并且FoodList等于FoodListOrder您必須首先創建FoodList陣列,然后創建(單個)Order物件。
var foodList = [FoodList]()
for item in subMenuList { // don't use an index based loop if you actually don't need the index
if item.foodList.foodSelectedAmount != 0 {
foodList.append(FoodList(foodName: item.foodList.foodName,
foodID: item.foodList.foodID,
foodAmount: item.foodList.foodSelectedAmount)
}
}
let order = Order(foodList: foodList,
name: mainView.nameTextField.text!,
phone: mainView.phoneTextField.text!,
email: mainView.emailTextField.text!)
let jsonEncoder = JSONEncoder()
do {
let jsonData = try jsonEncoder.encode(order)
print(String(data: jsonData, encoding: .utf8)!)
} catch {
print(error)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483811.html
