我一直在思考使用 Spring MVC 设计 JSON API 的最佳方法。众所周知,IO 很昂贵,因此我不想让客户端进行多次 API 调用来获得他们需要的东西。但与此同时,我不一定要归还厨房水槽。
例如,我正在开发一个类似于 IMDB 的游戏 API,但用于视频游戏。
如果我返回与 Game 相关的所有内容,它会看起来像这样。
/api/游戏/1
{
"id": 1,
"title": "Call of Duty Advanced Warfare",
"release_date": "2014-11-24",
"publishers": [
{
"id": 1,
"name": "Activision"
}
],
"developers": [
{
"id": 1,
"name": "Sledge Hammer"
}
],
"platforms": [
{
"id": 1,
"name": "Xbox One",
"manufactorer": "Microsoft",
"release_date": "2013-11-11"
},
{
"id": 2,
"name": "Playstation 4",
"manufactorer": "Sony",
"release_date": "2013-11-18"
},
{
"id": 3,
"name": "Xbox 360",
"manufactorer": "Microsoft",
"release_date": "2005-11-12"
}
],
"esrbRating": {
"id": 1,
"code": "T",
"name": "Teen",
"description": "Content is generally suitable for ages 13 and up. May contain violence, suggestive themes, crude humor, minimal blood, simulated gambling and/or infrequent use of strong language."
},
"reviews": [
{
"id": 1,
"user_id": 111,
"rating": 4.5,
"description": "This game is awesome"
}
]
}
然而,他们可能不需要所有这些信息,但他们可能再次需要。从 I/O 和性能来看,调用所有内容似乎是个坏主意。
我考虑通过在请求中指定包含参数来做到这一点。
现在例如,如果您没有指定任何包含,那么您将得到以下内容。
{
"id": 1,
"title": "Call of Duty Advanced Warfare",
"release_date": "2014-11-24"
}
但是,您希望您的请求的所有信息看起来像这样。
/api/game/1?include=publishers,developers,platforms,reviews,esrbRating
这样,客户就可以指定他们想要多少信息。但是,我对使用 Spring MVC 实现这一点的最佳方法感到不知所措。
我在想控制器看起来像这样。
public @ResponseBody Game getGame(@PathVariable("id") long id,
@RequestParam(value = "include", required = false) String include)) {
// check which include params are present
// then someone do the filtering?
}
我不确定您将如何选择序列化 Game 对象。这甚至可能吗。在 Spring MVC 中解决这个问题的最佳方法是什么?
仅供参考,我正在使用包含 Jackson 的 Spring Boot 进行序列化。