我有一个核心数据实体Checkout只有一个可转换的属性并设置为[String:Any]:
cart : [String:Any]
现在我使用此功能检索购物车中的商品:
func getCheckOutItems()-> [NSDictionary]{
let request : NSFetchRequest<Checkout> = Checkout.fetchRequest()
request.propertiesToFetch = ["cart"]
request.resultType = .dictionaryResultType
var checkout : [NSDictionary]!
var cart : [String:Any]!
do{
checkout = try context.fetch(request)
}catch{
print ("Error fetching data")
}
return checkout
}
现在我需要将这些项添加到字典中,该字典还包含其他项目:
var cart = [String:Any]()
cart["cart"] = getCheckOutItems()
cart["telco"] = "something"
cart["fcm_token"] = "tokden"
cart["email"] = "email"
let jsonData = try? JSONSerialization.data(withJSONObject: cart, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)
print("Printing JSON \(jsonString)")
这是为了产生这样的json结果:
{
"fcm_token": "tokden",
"cart": [{
"entity": 1,
"quantity": 1,
"id": 428,
"price": 80,
"date": "30 Jan 2018",
"seat_no": 20,
"type": "bus",
"item": "STANDARD",
"schedule_id": 132
},
{
"entity": 1,
"quantity": 1,
"id": 1539,
"price": 110,
"date": "30 Jan 2018",
"seat_no": 7,
"type": "bus",
"item": "EXECUTIVE",
"schedule_id": 131
},
{
"entity": 1,
"quantity": 1,
"id": 282,
"price": 40,
"date": "30 Jan 2018",
"seat_no": 1,
"type": "bus",
"item": "STANDARD",
"schedule_id": 114
}
],
"telco": "something",
"email": "email"
}
主要目的是确保当购物车物品附加到最终的json结果时,它们被作为一个带有钥匙&#34; cart&#34;的阵列附着。但是,由于我无法循环获取每个项目购物车,当我将其添加到JSON时,我得到的结果如下:
{
"fcm_token": "tokden",
"cart": [{
**"cart": {**
"entity": 1,
"quantity": 1,
"id": 428,
"price": 80,
"date": "30 Jan 2018",
"seat_no": 20,
"type": "bus",
"item": "STANDARD",
"schedule_id": 132
}
}, {
"cart": {
"entity": 1,
"quantity": 1,
"id": 1539,
"price": 110,
"date": "30 Jan 2018",
"seat_no": 7,
"type": "bus",
"item": "EXECUTIVE",
"schedule_id": 131
}
}, {
"cart": {
"entity": 1,
"quantity": 1,
"id": 282,
"price": 40,
"date": "30 Jan 2018",
"seat_no": 1,
"type": "bus",
"item": "STANDARD",
"schedule_id": 114
}
}],
"telco": "something",
"email": "email"
}
如何格式化此结果,以便&#34;购物车&#34;如前所述,删除了键以格式化json