将NSDictionary转换为JSON
我有一个核心数据实体签出,它只有一个可转换的属性,并设置为[String:Any]:将NSDictionary转换为JSON,json,swift,Json,Swift,我有一个核心数据实体签出,它只有一个可转换的属性,并设置为[String:Any]: cart : [String:Any] 以下函数用于从核心数据中检索值: func getCheckOutItems()-> [NSDictionary]{ let request : NSFetchRequest<Checkout> = Checkout.fetchRequest() request.propertiesToFetch = ["cart"] r
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
}
这是为了产生如下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"
}
主要的问题是,我需要从核心数据中删除键,该键突出显示为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。我对swift非常陌生,似乎很难理解这个问题。您可以使用flatMap。试试这个
let cartItems = getCheckOutItems() as? [[String:Any]]
var cart = [String:Any]()
cart["cart"] = cartItems?.flatMap({ $0.flatMap { $0.value } })
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)")
首先,使用Swift 4 Jain解析器
let cartItems = getCheckOutItems() as? [[String:Any]]
var cart = [String:Any]()
cart["cart"] = cartItems?.flatMap({ $0.flatMap { $0.value } })
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)")