将NSDictionary转换为JSON

时间:2018-01-29 06:51:46

标签: json swift

我有一个核心数据实体Checkout只有一个可转换的属性并设置为[String:Any]:

 cart : [String:Any]

以下函数用于从Core Data中检索值:

 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字符串中,该字符串还包含使用此函数的其他键:

 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"
}

主要问题是我需要从核心数据中删除密钥,该核心数据突出显示为“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,如前所述。我是一个非常新的快速,似乎很难围绕这个问题。

1 个答案:

答案 0 :(得分:1)

您可以使用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)")