Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

realm

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.

like image 356
petto Avatar asked Dec 20 '22 02:12

petto


1 Answers

I am also new to Realm but I think the easiest way is to reflect on Object's schema:

class Person: Object {
    dynamic var name = ""
    dynamic var age = 0
}

let person = Person()

let schema = person.objectSchema

let properties = schema.properties.map() { $0.name }

let dictionary = person.dictionaryWithValuesForKeys(properties) // NSDictionary

println(properties)
println(dictionary)
like image 132
Stanislav Pankevich Avatar answered Dec 28 '22 22:12

Stanislav Pankevich