gpt4 book ai didi

java - Spring Rest Controller 返回特定字段

转载 作者:IT老高 更新时间:2023-10-28 13:54:00 25 4
gpt4 key购买 nike

我一直在思考使用 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 和性能来看,对所有内容进行调用似乎是个坏主意。

我想通过在请求中指定包含参数来做到这一点。

现在,例如,如果您没有指定任何包含,那么您将返回以下内容。

{
"id": 1,
"title": "Call of Duty Advanced Warfare",
"release_date": "2014-11-24"
}

但是您希望您的请求的所有信息看起来像这样。

/api/game/1?include=publishers,developers,platforms,reviews,esrbRating

通过这种方式,客户可以指定他们想要多少信息。但是,我有点不知所措使用 Spring MVC 实现这一点的最佳方法。

我认为 Controller 应该是这样的。

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 进行序列化。

最佳答案

而不是返回 Game对象,您可以将其序列化为 Map<String, Object> ,其中映射键表示属性名称。因此,您可以根据 include 将值添加到 map 中。参数。

@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"
}
]
}

关于java - Spring Rest Controller 返回特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30558784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com