我正在使用 Sync 尝试将一些 JSON 解析为核心数据。
我的“Creature”实体具有如下所示的父子关系:
JSON 的格式与此类似:
[
{
"id": 1,
"name": "Mad king",
"parent": null,
"children": [
5
]
},
{
"id": 2,
"name": "Drogon",
"parent": 5,
"children": []
},
{
"id": 3,
"name": "Rhaegal",
"parent": 5,
"children": []
},
{
"id": 4,
"name": "Viserion",
"parent": 5,
"children": []
},
{
"id": 5,
"name": "Daenerys",
"parent": 1,
"children": [
2,
3,
4
]
}
]
疯狂国王有一个 child 丹妮莉丝,她有3个 child (卓耿、雷哥和韦塞里昂)。
现在,我知道 Sync 确实支持这种设置(其中 JSON 仅包含 parent / child 的 id,而不是整个对象),并且我怀疑我必须解析该文件两次 - 一次只获取所有对象第二个是建立它们之间的关系。为了使第二个工作正常,我需要将 children
重命名为 children_ids
,将 parent
重命名为 parent_id
(如 their README 中所述) )。
但是我不明白我到底该怎么做。是否可以在第一次传递期间忽略父/子项,然后在第二次传递期间考虑它们(使用修改后的键)?
或者有人可能会提出一个更好的解决方案,(理想情况下)只需要一次通过?
最佳答案
For example, in the one-to-many example, you have a user, that has many notes. If you already have synced all the notes then your JSON would only need the notes_ids, this can be an array of strings or integers. As a side-note only do this if you are 100% sure that all the required items (notes) have been synced, otherwise this relationships will get ignored and an error will be logged.
因此,从理论上讲,您可以盲目地执行完全同步来实际获取所有模型(让它在关系上失败),然后立即再次同步以获取关系。
如果您想避免错误,您可能需要编写一些辅助函数来为这些模型创建 2 组 JSON,一组用于定义对象,第二组用于定义关系。无论哪种方式,您都需要进行 2 遍。
关于ios - 如何使用 Sync 将 JSON 解析为与其自身有关系的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46186171/