Search code examples
swiftrealm

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 
}

Solution

  • 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 = [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
        }
    }