简体   繁体   中英

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

until version 10.7.6 of Realm I could convert to dictionary and then to json with this code below, but the ListBase class no longer exists.

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 
}

List now inherits from RLMSwiftCollectionBase apparently, so you can check for that instead. Also, this is Swift. Use [String: Any] instead of 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 = [[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
    }
}

Thanks to @Eduardo Dos Santos. Just do the following steps. You will be good to go.

  1. Change ListBase to RLMSwiftCollectionBase
  2. Change _rlmArray to _rlmCollection
  3. Import Realm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM