gpt4 book ai didi

json - 从 Core Data 获取 JSON 格式的特定项目

转载 作者:行者123 更新时间:2023-11-30 11:49:28 31 4
gpt4 key购买 nike

我有一个核心数据实体 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 结果时,它们附加为带有键“cart”的数组。但是,由于我无法循环获取每个商品购物车,因此当我将其添加到 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"

}

如何格式化此结果,以便消除“cart”键以格式化 json,如前所述

最佳答案

您可以使用此库将 json 保存到 coredata,反之亦然。

Click this link for the library 3Lvis Library

关于json - 从 Core Data 获取 JSON 格式的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48487561/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com