我应该删除JSON API响应中已经存在于`data`中的`included`模型吗?

时间:2017-04-16 22:25:31

标签: json serialization json-api

假设我有一个名为topics的模型,它是自引用的(主题通过其parent_topic_id属于主题)。

所以,我有一个名为sports的主题和一个名为basketball的儿童主题。

JSON API响应当前被序列化为:

{
  "data": [
    {
      "type": "topics",
      "id": "sports",
      "attributes": {
        "name": "Sports",
        "show-role-title": null,
        "created-at": "2017-04-16T21:19:25.000Z",
        "updated-at": null
      },
      "links": {
        "self": "/topics/sports"
      }
    },
    {
      "type": "topics",
      "id": "sports-basketball",
      "attributes": {
        "name": "Basketball",
        "show-role-title": null,
        "created-at": "2017-04-16T21:19:25.000Z",
        "updated-at": null
      },
      "relationships": {
        "parent-topic": {
          "data": {
            "type": "topics",
            "id": "sports"
          }
        }
      },
      "links": {
        "self": "/topics/sports-basketball"
      }
    }
  ],
  "included": [
    {
      "type": "topics",
      "id": "sports",
      "attributes": {
        "name": "Sports",
        "show-role-title": null,
        "parent-topic-id": null,
        "created-at": "2017-04-16T21:19:25.000Z",
        "updated-at": null
      },
      "links": {
        "self": "/topics/sports"
      }
    }
  ]
}

现在,考虑到sports已经在data,但basketball相关,是否也可以将其作为included附加记录?

1 个答案:

答案 0 :(得分:0)

在这种情况下,您应该拥有两个资源/topics/parentTopic,如果您的请求具有此类必要性,则在主对象和包含对象中具有相同的数据副本是有效的。在您的情况下,请求将为/topics?include=parentTopic

根据JSON API spec,包含不是强制性的。我的建议是/topics很好,您可以从/topics关系(取决于客户端框架)引用父主题数据,如果您查询特定资源记录,则可以添加包含/topics/sports-basketball?include=parentTopic < / p>