I\'ve been going through my head the best way to design a JSON API using Spring MVC. As we all know IO is expensive, and thus I don\'t want to make the client make several A
This can be done by Spring Projections
. Also works fine with Kotlin.
Take a look here: https://www.baeldung.com/spring-data-jpa-projections
Instead of returning a Game
object, you could serialize it as as a Map<String, Object>
, where the map keys represent the attribute names. So you can add the values to your map based on the include
parameter.
@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;
}
As an example, if you have a Map<String, Object>
like this:
gameMap.put("id", game.getId());
gameMap.put("title", game.getTitle());
gameMap.put("publishers", game.getPublishers());
It would be serialized like this:
{
"id": 1,
"title": "Call of Duty Advanced Warfare",
"publishers": [
{
"id": 1,
"name": "Activision"
}
]
}
Being aware that my answer comes quite late: I'd recommend to look at Projections
.
What you're asking for is what projections are about.
Since you're asking about Spring I'd give this one a try: https://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts