swift - 从 Meteor JSON/Array/Cursor 创建字典数组

标签 swift

我从数组中的 Meteor 服务器接收了几个(0-10)个对象。它们在控制台中可能看起来像这样:

let allConferences = conferences.allDocuments
print(allConferences)

控制台输出:

[<METDocument key: <collection: conferences, ID: Hr3bw6pySG8G3TKzh>, fields: {
    createdAt = "2015-11-03 13:43:05 +0000";
    type = doctor;
    user = KTsCySacEAiz3eDnf;
    userdata =     {
        birthdate = "Male";
        gender = "<null>";
    };
}>, <METDocument key: <collection: conferences, ID: RmfQm96Kcj5JTfDQM>, fields: {
    createdAt = "2015-11-03 13:40:12 +0000";
    type = doctor;
    user = KTsCySacEAiz3eDnf;
    userdata =     {
        birthdate = "<null>";
        gender = "<null>";
    };
}>]

我需要以我可以在 Swift 2.1 中轻松使用的格式获取这些数据。例如,我需要根据 createdAt 字段对对象进行排序,然后在 tableView 的标签中使用其他一些字段。

我已经根据 this answer 尝试了 NSJSONSerialization

do {
    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(allConferences, options: []) as? NSDictionary {
    print(jsonResult)
    }
} catch {
    print(error)
    }

但这给了我错误 Cannot convert value of type '[AnyObject]' to expected argument type 'NSData'

我可以用这个方法直接访问字段区域:

let oneConferencesField: NSDictionary = conferences.allDocuments[0].valueForKey("fields") as! NSDictionary

如果有人知道如何按照使用 NSJSONSerialization 的经典方法解析此数据,那就太好了 - 谢谢。

最佳答案

NSJSONSerialization.JSONObjectWithData 仅适用于 JSON 数据(例如,来自服务器)。您的 allConferences 对象是 METDocument 对象的数组,而不是数据,因此它不起作用是正常的。

通读文档,您似乎可以通过使用其 fields 从 METDocument 中获取字典。属性(property)。

所以要从你的对象中提取字典,你可以这样做:

var dicts: [[String:AnyObject]] = []
for document in conferences.allDocuments {
    if let fields = document.fields as? [String:AnyObject] {
        dicts.append(fields)
    }
}

关于swift - 从 Meteor JSON/Array/Cursor 创建字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33503422/

相关文章:

ios - UILabel高度计算

Swift:没有这样的模块 "GoogleMaps"错误

ios - 使用 Codable (Swift) 从 Json 文件中解析 UIColor

ios - 在 iOS 上检测没有 Vision Framework 的纸张和文本

ios - 如何将UITableView放在UIView中

ios - viewDidEnd() 方法可以快速实现吗?

swift - 为什么 swift 不使用没有类型约束的通用返回参数来推断适当的重载函数?

ios - 如何向下移动textView光标?

ios - 无法创建具有自定义约束的贴纸浏览器

ios - ReactiveSwift 刷新数据