Search code examples
iosswiftrealm

Can I serialize a RealmObject to JSON or to NSDictionary in Realm for Swift?


I'm testing Realm, but I cant find a easy way to convert my object to JSON. I need to push the data to my REST interface. How can I do it using swift?

class Dog: Object {
  dynamic var name = ""
}

class Person : Object {
  dynamic var name = ""
  let dogs = List<Dog>()
}

I'm trying something like this, but I can't iterate unknown objects (List)

extension Object {
  func toDictionary() -> NSDictionary {
    let props = self.objectSchema.properties.map { $0.name }
    var dicProps = self.dictionaryWithValuesForKeys(props)

    var mutabledic = NSMutableDictionary()
    mutabledic.setValuesForKeysWithDictionary(dicProps)

    for prop in self.objectSchema.properties as [Property]! {

      if let objectClassName = prop.objectClassName  {
        if let x = self[prop.name] as? Object {
          mutabledic.setValue(x.toDictionary(), forKey: prop.name)
        } else {
          //problem here!
        }
      }
    }
    return mutabledic
  }
}

**sorry for ugly code.


Solution

  • I think that I found the solution. I'm not reliant about performance.

    extension Object {
      func toDictionary() -> NSDictionary {
        let properties = self.objectSchema.properties.map { $0.name }
        let dicProps = self.dictionaryWithValuesForKeys(properties)
    
        var mutabledic = NSMutableDictionary()
        mutabledic.setValuesForKeysWithDictionary(dicProps)
    
        for prop in self.objectSchema.properties as [Property]! {
    
          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
      }
    }