java - Spring Rest Controller Return Specific Fields -
i've been going through head best way design json api using spring mvc. know io expensive, , don't want make client make several api calls need. @ same time don't want return kitchen sink.
as example working on game api similar imdb video games instead.
if returned connected game this.
/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 suitable ages 13 , 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 awesome" } ] }
however may not need information, again might. making calls seems bad idea i/o , performance.
i thought doing specifying include parameter in requests.
now example if did not specify includes following.
{ "id": 1, "title": "call of duty advanced warfare", "release_date": "2014-11-24" }
however want information requests this.
/api/game/1?include=publishers,developers,platforms,reviews,esrbrating
this way client has ability specify how information want. i'm kind of @ loss best way implement using spring mvc.
i'm thinking controller this.
public @responsebody game getgame(@pathvariable("id") long id, @requestparam(value = "include", required = false) string include)) { // check include params present // filtering? }
i'm not sure how optionally serialize game object. possible. best way approach in spring mvc?
fyi, using spring boot includes jackson serialization.
instead of returning game
object, serialize as map<string, object>
, map keys represent attribute names. can add values map based on include
parameter.
@responsebody public map<string, object> getgame(@pathvariable("id") long id, string include) { game game = service.loadgame(id); // check `include` parameter , create map containing required attributes map<string, object> gamemap = service.convertgametomap(game, include); return gamemap; }
as example, if have map<string, object>
this:
gamemap.put("id", game.getid()); gamemap.put("title", game.gettitle()); gamemap.put("publishers", game.getpublishers());
it serialized this:
{ "id": 1, "title": "call of duty advanced warfare", "publishers": [ { "id": 1, "name": "activision" } ] }
Comments
Post a Comment