多个Realm对象为JSON

时间:2018-02-27 20:51:28

标签: swift realm

我正在尝试将Realm Object转换为JSON。我的版本正在运行,但如果您想将多个对象放入JSON中则不行。所以我的问题是,你应该如何将多个Realm对象添加到JSON中?

类似的东西:

@Override
public void onStop(){
    super.onStop();
    finish();
    System.runFinalizersOnExit(true);
    System.exit(0);
    android.os.Process.killProcess(android.os.Process.myPid());
}`

这就是我现在正在做的事情:

{
"Users": [
{"id": "1","name": "John"},{"id": "2","name": "John2"},{"id": "3","name": "John3"}
],
"Posts": [
{"id": "1","title": "hey"},{"id": "2","title": "hey2"},{"id": "3","title": "hey3"}
]
}

上面的函数就是这样,这只适用于一个对象:

func getRealmJSON(name: String, realmObject: Object, realmType: Any) -> String {
        do {
            let realm = try Realm()
            let table = realm.objects(realmType as! Object.Type)
            if table.count == 0 {return "Empty Table"}
            let mirrored_object = Mirror(reflecting: realmObject)
            var properties = [String]()
            for (_, attr) in mirrored_object.children.enumerated() {
                if let property_name = attr.label as String! {
                    properties.append(property_name)
                }
            }
            var jsonObject = "{\"\(name)\": ["
            for i in 1...table.count {
                var str = "{"
                var insideStr = String()
                for property in properties {
                    let filteredTable = table.value(forKey: property) as! [Any]
                    insideStr += "\"\(property)\": \"\(filteredTable[i - 1])\","
                }
                let index = insideStr.characters.index(insideStr.startIndex, offsetBy: (insideStr.count - 2))
                insideStr = String(insideStr[...index])
                str += "\(insideStr)},"
                jsonObject.append(str)
            }
            let index = jsonObject.characters.index(jsonObject.startIndex, offsetBy: (jsonObject.count - 2))
            jsonObject = "\(String(jsonObject[...index]))]}"
            return jsonObject
        }catch let error { print("\(error)") }
        return "Problem reading Realm"
    }

像这样我称之为:

{"Users": [{"id": "1","name": "John"},{"id": "2","name": "John2"},{"id": "3","name": "John3"}]}

我试图附上它们。

有人可以带我走上正确的轨道吗?

1 个答案:

答案 0 :(得分:0)

您可以使用数据模型对数据进行编码/解码: 例如,你有

class UserEntity: Object {

    @objc dynamic var id: String = ""
    @objc dynamic var createdAt: Date = Date()

    @objc private dynamic var addressEntities = List<AddressEntity>()
    var addresses: [Address] {
        get {
            return addressEntities.map { Address(entity: $0) }
        }
        set {
            addressEntities.removeAll()
            let newEntities = newValue.map { AddressEntity(address: $0) }
            addressEntities.append(objectsIn: newEntities)
        }
    }
}

在这里,您使用private隐藏 addressEntities ,并使用Address结构类型声明地址 var,以将实体映射到正确的值; 然后使用

struct User: Codable {
    let id: String
    let createdAt: Date
    let addresses: [Address]
}

然后以任何方式编码User struct