Skip to content
Advertisement

Spring Rest Controller Return Specific Fields

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 API calls to get what they need. However at the same time I don’t necessarily want to return the kitchen sink.

As an example I was working on a game API similar to IMDB but for video games instead.

If I returned everything connected to Game it would look something like this.

/api/game/1

JavaScript

However they may not need all this information, but then again they might. Making calls for everything seems like a bad idea from I/O and performance.

I thought about doing it by specifying include parameter in the requests.

Now for example if you did not specify any includes all you would get back is the following.

JavaScript

However it you want all the information your requests would look something like this.

JavaScript

This way the client has the ability to specify how much information they want. However I’m kind of at a loss the best way to implement this using Spring MVC.

I’m thinking the controller would look something like this.

JavaScript

I’m not sure how you would optionally serialize the Game object. Is this even possible. What is the best way to approach this in Spring MVC?

FYI, I am using Spring Boot which includes Jackson for serialization.

Advertisement

Answer

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.

JavaScript

As an example, if you have a Map<String, Object> like this:

JavaScript

It would be serialized like this:

JavaScript
Advertisement