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

How convert Realm data to Json on Swift? Realm version 10.11.0

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

extension Object {
func toDictionary() -> NSDictionary {
    let properties = self.objectSchema.properties.map { [=12=].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 
}

List 现在显然继承自 RLMSwiftCollectionBase,因此您可以检查一下。另外,这是Swift。使用 [String: Any] 而不是 NSDictionary.

extension Object {
    func toDictionary() -> [String: Any] {
        let properties = self.objectSchema.properties.map { [=10=].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 = [[String: Any]]()
                for index in 0..<nestedListObject._rlmCollection.count  {
                    let object = nestedListObject._rlmCollection[index] as! Object
                    objects.append(object.toDictionary())
                }
                mutabledic[prop.name] = objects
            }
        }
        return mutabledic
    }
}