Spring Rest Controller Return Specific Fields

前端 未结 3 2051
有刺的猬
有刺的猬 2020-12-09 09:31

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

相关标签:
3条回答
  • 2020-12-09 10:19

    This can be done by Spring Projections. Also works fine with Kotlin. Take a look here: https://www.baeldung.com/spring-data-jpa-projections

    0 讨论(0)
  • 2020-12-09 10:20

    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"
        }
      ]
    }
    
    0 讨论(0)
  • 2020-12-09 10:30

    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

    0 讨论(0)
提交回复
热议问题