在JSON中为移动API表示子对象

时间:2014-06-09 23:04:49

标签: json api rest sync

我正在为移动应用设计JSON API,并且必须决定如何在服务器上向客户端显示子对象。通常,从客户端到服务器的请求将是单个同步请求,并且响应将包括需要更新的所有对象。展示物品的最佳方式是什么?

选项A - 嵌套儿童:

{ "articles": [
{ "id" : 1,
  "title": "This is the first article",
  "comments": [
      {"id": "1",
       "article_id" : "1",
       "title": "A comment on the first article"
      }]
},
{ "id" : 2,
  "title": "This is the second article",
  "comments": [
      {"id": "2",
       "article_id" : "2",
       "title": "A comment on the second article"
      }]
}, ]}

选项B - 自己拥有的所有物品

{ "articles": [
  { "id" : 1,
    "title": "This is the first article",
  }
  { "id" : 2,
    "title": "This is the second article",
  }]
 "comments": [
  {"id": "1",
   "article_id" : "1",
   "title": "A comment on the first article"
  },
  {"id": "2",
   "article_id" : "2",
   "title": "A comment on the second article"
  }]}

在客户端,我可以处理任一格式并根据article_id字段构建关系,所以我不太清楚为什么要嵌套孩子,除了它使它看起来不错。但是,当我考虑为客户端编写测试时,尤其是json到对象的映射时,似乎更容易显示和映射每个对象。我是初学者,所以任何想法都会有所帮助。

PS。我正在使用Rails / Grape和使用RestKit / Coredata(iOS)以及可能是RoboSpice / ORMLite(Android)的客户端构建服务器。

1 个答案:

答案 0 :(得分:2)

这是非常主观的。对此没有一个正确的答案。这实际上取决于哪种方法更适合您的任务和数据。您说这是用于同步数据的请求。如何在客户端表示和存储数据?如果是平坦的,就像关系数据库一样,则平面输出可能更容易使用。另一方面,如果客户端将大量使用这些关系,那么使用嵌套结构可能会更好。

从API设计的角度来看,我会让文章集合的端点接受像expand这样的查询参数,带有级别编号或命名实体,并且它会相应地添加嵌套子项。因此,例如,GET /api/articles?expand=comments将生成具有嵌套注释的输出,或GET /api/articles?expand=1以生成具有所有直接子项的输出。这样,客户端可以在需要时轻松生成嵌套输出,或者他们可以单独查询端点以查找文章和注释,并在需要平面数据时连接输出。