如何在Swift中将Realm对象转换为JSON?

如何在Swift中将Realm对象转换为JSON?,第1张

如何在Swift中将Realm对象转换为JSON?

设法在这里找到答案:

我可以在Realm forSwift中将RealmObject序列化为JSON或NSDictionary吗?

extension Object {func toDictionary() -> NSDictionary {    let properties = self.objectSchema.properties.map { 
extension Object {func toDictionary() -> NSDictionary {    let properties = self.objectSchema.properties.map { 
extension Object {func toDictionary() -> NSDictionary {    let properties = self.objectSchema.properties.map { .name }    let dictionary = self.dictionaryWithValues(forKeys: properties)    let mutabledic = NSMutableDictionary()    mutabledic.setValuesForKeys(dictionary)    for prop in self.objectSchema.properties as [Property]! {        // find lists        if let nestedObject = self[prop.name] as? Object { mutabledic.setValue(nestedObject.toDictionary(), forKey: prop.name)        } else if let nestedListObject = self[prop.name] as? Listbase { var objects = [AnyObject]() for index in 0..<nestedListObject._rlmArray.count  {     let object = nestedListObject._rlmArray[index] as AnyObject     objects.append(object.toDictionary()) } mutabledic.setObject(objects, forKey: prop.name as NSCopying)        }    }    return mutabledic}}
.name } let dictionary = self.dictionaryWithValuesForKeys(properties) let mutabledic = NSMutableDictionary() mutabledic.setValuesForKeysWithDictionary(dictionary) for prop in self.objectSchema.properties as [Property]! { // find lists if let nestedObject = self[prop.name] as? Object { mutabledic.setValue(nestedObject.toDictionary(), forKey: prop.name) } else if let nestedListObject = self[prop.name] as? Listbase { var objects = [AnyObject]() for index in 0..<nestedListObject._rlmArray.count { let object = nestedListObject._rlmArray[index] as AnyObject objects.append(object.toDictionary()) } mutabledic.setObject(objects, forKey: prop.name) } } return mutabledic}}
.name } let dictionary = self.dictionaryWithValuesForKeys(properties) var mutabledic = NSMutableDictionary() mutabledic.setValuesForKeysWithDictionary(dictionary) for prop in self.objectSchema.properties as [Property]! { // find lists if let objectClassName = prop.objectClassName { if let nestedObject = self[prop.name] as? Object { mutabledic.setValue(nestedObject.toDictionary(), forKey: prop.name) } else if let nestedListObject = self[prop.name] as? Listbase { var objects = [AnyObject]() for index in 0..<nestedListObject._rlmArray.count { if let object = nestedListObject._rlmArray[index] as? Object { objects.append(object.toDictionary()) } } mutabledic.setObject(objects, forKey: prop.name) } } } return mutabledic}}
Xpre 7和Swift 2的更新:
更新到Xpre 8和Swift 3:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642241.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存