解析NSDictionary在Core Data中按提取请求分组的结果

时间:2017-06-23 16:10:33

标签: ios json swift core-data

我需要使用CoreData从表中获取一些统计信息。我使用this手册使用“group by”表达式提取数据。

这是我的源代码:

var popularGuestNames: [String] = []
        let keypathExp = NSExpression(forKeyPath: "guestName")
        let expression = NSExpression(forFunction: "count:", arguments: [keypathExp])

        let countDesc = NSExpressionDescription()
        countDesc.expression = expression
        countDesc.name = "count"
        countDesc.expressionResultType = .integer64AttributeType

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "GuestsTable")
        request.returnsObjectsAsFaults = false
        request.propertiesToGroupBy = ["guestName"]
        request.propertiesToFetch = ["guestName", countDesc]
        request.resultType = .dictionaryResultType

        let matchedGuests = try? context.fetch(request)
        guard matchedGuests != nil else {return popularGuestNames}

但是作为结果我得到匹配的游戏类型[任意]。我卡在这里。我可以看到使用print有JSON对象:

Optional(
[{
    count = 1;
    guestName = "\U0412\U0430\U043d\U044f";
}, {
    count = 13;
    guestName = "\U0413\U043e\U0441\U0442\U044c 1";
}, {
    count = 9;
    guestName = "\U0413\U043e\U0441\U0442\U044c 2";
}, {
    count = 3;
    guestName = "\U0413\U043e\U0441\U0442\U044c 3";
}, {
    count = 1;
    guestName = "\U0413\U043e\U0441\U0442\U044c 4";
}, {
    count = 1;
    guestName = "\U0413\U043e\U0441\U0442\U044c 5";
}, {
    count = 1;
    guestName = "\U041d\U043d\U043d";
}, {
    count = 1;
    guestName = "\U0422\U0435\U0441\U0442";
}, {
    count = 1;
    guestName = "\U0422\U0435\U0441\U0442 \U0442\U0435\U0441\U0442\U043e\U0432\U0438\U0447";
}, {
    count = 1;
    guestName = "\U0423\U0410\U0443\U043f\U0430\U0438\U0443\U0430\U0433\U0443";
}])

但我找不到如何解析它的方法。我知道我应该使用JSONSerialization.jsonObject,但是这个方法需要Data类型中的输入变量。我无法理解如何将Any转换为数据。

2 个答案:

答案 0 :(得分:3)

首先,核心数据提取的结果肯定是不是一个JSON对象

其次更具体!

由于获取请求的返回类型显然是字典,因此使用泛型类型来传递NSDictionary

let request = NSFetchRequest<NSDictionary>(entityName: "GuestsTable")

然后将类型转换为实际类型[[String:Any]]

var matchedGuests = [[String:Any]]()
...
if let result = try? context.fetch(request) as! [[String:Any]] {
   matchedGuests = result
} 

即使发生try?错误,强制解包返回类型也不会导致崩溃,假设获取请求有效。

如果您只想要客人名称map数组

let popularGuestNames = matchedGuests.flatMap { $0["guestName"] as? String }

答案 1 :(得分:1)

matchedGuests是一个词典数组,或[[String:Any]]。要使用它,您可以使用for in循环迭代它。

for dic in matchedGuests {
    //Dic will be a dictionary in the array with key value pairs.
    print(dic["count"])
    print(dic["guestName"])
    .... do more work with results.
}

如果您知道它的类型,则使用Any的值将其转换为String。

let string = dic["guestName"] as? String