使用基于 ID 的关系将 JSON 中的对象插入到 Realm 中
Insert object from JSON into Realm with relation based on ID
我想从我的服务器获取一些对象并将它们作为 JSON 对象接收并使用 insertOrUpdate()
添加到领域。
目前,嵌套/相关对象由服务器整体发送,领域会神奇地插入它们并将它们相互关联 - 工作完美。
我从服务器收到的 Foo
列表如下所示(Bar
为每个引用复制):
[
{
"id": 1,
"name": "Foo 1",
"bar": [
{
"id": 1,
"name": "Bar 1"
},
{
"id": 2,
"name": "Bar 2"
}
]
},
{
"id": 2,
"name": "Foo 2",
"bar": [
{
"id": 2,
"name": "Bar 2"
}
]
}
]
但这意味着要传输更多数据,因为共享对象(例如 Bar
和 ID 2
)在 JSON.
中重复
有没有办法让 JSON 中只有共享对象的 ID,但让领域 link 它们指向正确的对象?
因此 JSON 中只说明了引用对象的 ID(我还需要获取这些对象 - 也许之前?):
[
{
"id": 1,
"name": "Foo 1",
"bar": [
1,
2
]
},
{
"id": 2,
"name": "Foo 2",
"bar": [
2
]
}
]
这可能吗?当共享许多/大对象时减少流量的最佳做法是什么?
当然有可能,但前提是您显然需要更改 API 生成的 JSON,因此它需要是一个 API控制。
我认为这是一种相当标准的工作方法,当然也是我实现这一目标的方法。您基本上要将一个 API ('get all foos and bars') 更改为两个 API('get all foos' 和 'get all bars')。 'get all foos' 的输出与您在上一个代码块中显示的几乎完全一样,'get all bars' 看起来类似于以下内容:
[
{
"id": 1,
"name": "Bar 1"
},
{
"id": 2,
"name": "Bar 2"
}
...
]
然后您需要更改 Realm 模型以反映预期的 JSON,特别是您具有 Foo 和 Bar RealmObject 类型。例如。 (科特林):-
open class Foo : RealmObject()
{
@PrimaryKey
var id: Int = 0
var name: String? = null
var bars: RealmList<Integer> = RealmList()
}
open class Bar : RealmObject()
{
@PrimaryKey
var id: Int = 0
var name: String? = null
}
然后您可以向 Foo
class 添加一个方法,以使用 this API 检索相关的 Bar
对象,例如如果顺序不重要(请原谅任何编译错误,现在无法测试):-
open class Foo : RealmObject()
{
...
val allBars: RealmResults<Bar>
get() = this.realm
.where(Bar::class.java)
.in("id", this.bars.toArray(arrayOf<Int>()))
.findAll()
}
我想从我的服务器获取一些对象并将它们作为 JSON 对象接收并使用 insertOrUpdate()
添加到领域。
目前,嵌套/相关对象由服务器整体发送,领域会神奇地插入它们并将它们相互关联 - 工作完美。
我从服务器收到的 Foo
列表如下所示(Bar
为每个引用复制):
[
{
"id": 1,
"name": "Foo 1",
"bar": [
{
"id": 1,
"name": "Bar 1"
},
{
"id": 2,
"name": "Bar 2"
}
]
},
{
"id": 2,
"name": "Foo 2",
"bar": [
{
"id": 2,
"name": "Bar 2"
}
]
}
]
但这意味着要传输更多数据,因为共享对象(例如 Bar
和 ID 2
)在 JSON.
有没有办法让 JSON 中只有共享对象的 ID,但让领域 link 它们指向正确的对象?
因此 JSON 中只说明了引用对象的 ID(我还需要获取这些对象 - 也许之前?):
[
{
"id": 1,
"name": "Foo 1",
"bar": [
1,
2
]
},
{
"id": 2,
"name": "Foo 2",
"bar": [
2
]
}
]
这可能吗?当共享许多/大对象时减少流量的最佳做法是什么?
当然有可能,但前提是您显然需要更改 API 生成的 JSON,因此它需要是一个 API控制。
我认为这是一种相当标准的工作方法,当然也是我实现这一目标的方法。您基本上要将一个 API ('get all foos and bars') 更改为两个 API('get all foos' 和 'get all bars')。 'get all foos' 的输出与您在上一个代码块中显示的几乎完全一样,'get all bars' 看起来类似于以下内容:
[
{
"id": 1,
"name": "Bar 1"
},
{
"id": 2,
"name": "Bar 2"
}
...
]
然后您需要更改 Realm 模型以反映预期的 JSON,特别是您具有 Foo 和 Bar RealmObject 类型。例如。 (科特林):-
open class Foo : RealmObject()
{
@PrimaryKey
var id: Int = 0
var name: String? = null
var bars: RealmList<Integer> = RealmList()
}
open class Bar : RealmObject()
{
@PrimaryKey
var id: Int = 0
var name: String? = null
}
然后您可以向 Foo
class 添加一个方法,以使用 this API 检索相关的 Bar
对象,例如如果顺序不重要(请原谅任何编译错误,现在无法测试):-
open class Foo : RealmObject()
{
...
val allBars: RealmResults<Bar>
get() = this.realm
.where(Bar::class.java)
.in("id", this.bars.toArray(arrayOf<Int>()))
.findAll()
}