如何在Swift中将Realm对象转换为JSON?

时间:2015-08-15 09:05:58

标签: json swift realm

我声明了两个Realm表:

class Task: Object {
    dynamic var taskID: String = ""
    let taskAssignedTo = List<Contacts>()
}

class Contacts: Object {
    dynamic var contactEmail: String = ""
    dynamic var contactName: String = ""
}

最终目标是将Task Realm对象转换为JSON。我想到的方法是:

使用类

中的方法将对象转换为字典
func taskToDictionary() -> [String: AnyObject] {
    return [
        "taskID" : self.taskID,
        "taskAssignedTo" : self.taskAssignedTo._rlmArray.count //Not sure how to get the array
    ]
}

使用SwiftyJSON将结果字典转换为JSON

let taskObject = Task()
let newTaskJSON = JSON(taskObject.taskToDictionary())

现在,这转换为ok,但是:

  1. 有更好的方法吗?
  2. 如何将RLMArray转换为JSON转换数组?

2 个答案:

答案 0 :(得分:1)

我无法评论,@ Eric

基于@Eugene Teh回答 我必须为约会做一个特定的治疗。这是我的代码(swift 3)

我先得到了值

if  let value = self.value(forKey: props.name) {
    if props.type == .date {
        mutabledic[props.name] = (value as! Date).timeIntervalSince1970
        //for using like the example, this should work
        //mutabledic.setObject( (value as! Date).timeIntervalSince1970, forKey: prop.name as NSCopying)
    }
    [..]//other case
}

答案 1 :(得分:1)

Swift 4.2 Xcode 11

这是我解决问题的方式。将领域对象转换为JSON数组以发送到Rest API 要求- SwiftyJSON

func getJsonArray(){
        var dicArray = [Dictionary<String,AnyObject>]()
        for item in cartsData! {
             dicArray.append(item.toDictionary())
        }
        print(JSON(dicArray))
    }

cartsData -var cartsData:结果<...>?

extension Object {
    func toDictionary() -> [String:AnyObject] {
        let properties = self.objectSchema.properties.map { $0.name }
        var dicProps = [String:AnyObject]()
        for (key, value) in self.dictionaryWithValues(forKeys: properties) {
            //key = key.uppercased()
            if let value = value as? ListBase {
                dicProps[key] = value.toArray1() as AnyObject
            } else if let value = value as? Object {
                dicProps[key] = value.toDictionary() as AnyObject
            } else {
                dicProps[key] = value as AnyObject
            }
        }
        return dicProps
    }
}

extension ListBase {
    func toArray1() -> [AnyObject] {
        var _toArray = [AnyObject]()
        for i in 0..<self._rlmArray.count {
            let obj = unsafeBitCast(self._rlmArray[i], to: Object.self)
            _toArray.append(obj.toDictionary() as AnyObject)
        }
        return _toArray
    }
}