Spring Rest Controller返回特定字段


问题内容

我一直在思考使用Spring MVC设计JSON
API的最佳方法。众所周知,IO很昂贵,因此我不想让客户端进行多个API调用来获取所需的东西。但是,与此同时,我不一定要归还厨房水槽。

举例来说,我正在开发类似于IMDB的游戏API,但用于视频游戏。

如果我退回与Game相关的所有内容,它将看起来像这样。

/ api / game / 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和性能来看,对所有内容进行调用似乎是一个坏主意。

我考虑过通过在请求中指定include参数来做到这一点。

现在,例如,如果您未指定任何包含,您将得到的所有内容如下。

{
    "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中解决此问题的最佳方法是什么?

仅供参考,我使用的是Spring Boot,其中包含Jackson进行序列化。


问题答案:

除了返回Game对象外,您还可以将其序列化为Map<String, Object>,其中映射键代表属性名称。因此,您可以根据include参数将值添加到地图中。

@ResponseBody
public Map<String, Object> getGame(@PathVariable("id") long id, String include) {

    Game game = service.loadGame(id);
    // check the `include` parameter and create a map containing only the required attributes
    Map<String, Object> gameMap = service.convertGameToMap(game, include);

    return gameMap;

}

例如,如果您有一个Map<String, Object>类似这样的人:

gameMap.put("id", game.getId());
gameMap.put("title", game.getTitle());
gameMap.put("publishers", game.getPublishers());

它将像这样被序列化:

{
  "id": 1,
  "title": "Call of Duty Advanced Warfare",
  "publishers": [
    {
        "id": 1,
        "name": "Activision"
    }
  ]
}