如何在 Swift 上将 Realm 数据转换为 Json?领域版本 10.11.0

问题描述 投票:0回答:2

直到 Realm 版本 10.7.6 为止,我可以使用下面的代码转换为字典,然后转换为 json,但 ListBase 类不再存在。

extension Object {
func toDictionary() -> NSDictionary {
    let properties = self.objectSchema.properties.map { $0.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 { /*Cannot find type 'ListBase' in scope*/
            var objects = [AnyObject]()
            for index in 0..<nestedListObject._rlmArray.count  {
                let object = nestedListObject._rlmArray[index] as! Object
                objects.append(object.toDictionary())
            }
            mutabledic.setObject(objects, forKey: prop.name as NSCopying)
        }
    }
    return mutabledic
}

}

let parameterDictionary = myRealmData.toDictionary()
guard let postData = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
  return 
}
swift realm
2个回答
5
投票

List
现在显然继承自
RLMSwiftCollectionBase
,因此您可以检查它。另外,这是斯威夫特。使用
[String: Any]
代替
NSDictionary

extension Object {
    func toDictionary() -> [String: Any] {
        let properties = self.objectSchema.properties.map { $0.name }
        var mutabledic = self.dictionaryWithValues(forKeys: properties)
        for prop in self.objectSchema.properties as [Property] {
            // find lists
            if let nestedObject = self[prop.name] as? Object {
                mutabledic[prop.name] = nestedObject.toDictionary()
            } else if let nestedListObject = self[prop.name] as? RLMSwiftCollectionBase {
                var objects = [Any]()
                for index in 0..<nestedListObject._rlmCollection.count  {
                    if let object = nestedListObject._rlmCollection[index] as? Object {
                        objects.append(object.toDictionary())
                    } else { // handle things like List<Int>
                        objects.append(nestedListObject._rlmCollection[index])
                    }
                }
                mutabledic[prop.name] = objects
            }
        }
        return mutabledic
    }
}

0
投票

感谢@Eduardo Dos Santos。 只需执行以下步骤即可。你会很高兴去的。

  1. 将 ListBase 更改为 RLMSwiftCollectionBase
  2. 将 _rlmArray 更改为 _rlmCollection
  3. 导入领域
© www.soinside.com 2019 - 2024. All rights reserved.