多个Realm对象为JSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多个Realm对象为JSON相关的知识,希望对你有一定的参考价值。
我试图将Realm对象转换为JSON。我的版本正在运行,但如果您想将多个对象放入JSON中则不行。所以我的问题是,你应该如何将多个Realm对象添加到JSON中?
像这样的东西:
{
"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"}]}
像这样我称之为:
let users = getRealmJSON(name: "Users", realmObject: Users(), realmType: Users.self)
let posts = getRealmJSON(name: "Posts", realmObject: Posts(), realmType: Posts.self)
我试着附上它们。
有人可以带我走上正轨吗?
答案
您可以使用数据模型对数据进行编码/解码:例如,您有
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
以上是关于多个Realm对象为JSON的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 中将 Realm 对象转换为 JSON?
Realm和RecyclerView项目排序和自动ViewPager片段通信