ios - 如何使用 Sync 将 JSON 解析为与其自身有关系的实体?

标签 ios json swift parsing core-data

我正在使用 Sync 尝试将一些 JSON 解析为核心数据。

我的“Creature”实体具有如下所示的父子关系:

enter image description here

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 中所述) )。

但是我不明白我到底该怎么做。是否可以在第一次传递期间忽略父/子项,然后在第二次传递期间考虑它们(使用修改后的键)?

或者有人可能会提出一个更好的解决方案,(理想情况下)只需要一次通过?

最佳答案

根据documentation:

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/

相关文章:

javascript - 在创建时将 JSON 发送到页面的最佳方式

IOS 状态栏 LigthContent

ios - Xcode 7 和基于 swift 的框架

ios - 生成PDF时如何将图像Url转换为pdf?

java - Json字符串反序列化为复杂的Java对象

javascript - 使用 Three.js 在形状上显示图像时出错

ios - UISegmentedControl 粘滞模式

ios - 在 Swift 中解析 CSV 文件

关于字典访问的 Swift 语义

ios - 无法将 'NSLayoutConstraint' 类型的不可变值作为 inout 参数传递