In our Spring application we're using Jackson to render the JSON responses of the controllers.
For some endpoints we want to adapt the rendering behaviour and only render the id field of certain objects.
Example
We have 3 objects types (OuterObject, ValueObject, InnerObject). Each has a "id" field beside other fields.
Normal rendering of the JSON object:
{
"id": 1,
"name": "outerObject name",
"valueObject": {
"id": 11,
"name": "valueObject 11",
"innerObj": {
"id" : 111,
"name" : "innerObject 111"
}
}
}
Special rendering of the JSON object ("name" field of the inner object is skipped)
{
"id": 1,
"namne": "obj name",
"valueObj": {
"id": 11,
"name": "valueObj 11",
"innerObj": {
"id" : 111
}
}
}
So as you can see, we want to only render the id of certain objects, but only if they are nested. So in the example we want to only render the id field of the inner object.
But if another endpoint would return inner objects then we want to render the whole object.
I saw that Jackson offers many annotations to control the behaviour of how fields get rendered. But as far as I understand them they are all forcing a static behaviour which we don't want.
Because we have many of these records (about 400), we don't want to create a second variation for each objects that only contains the id field. Our approach is to reuse the current logic to build and populate these objects, and throw certain fields away when we serialise the object to a JSON string.
Update
I don't think that @JsonView annotation could solve that issue, as only one view at a time could be used for rendering the response.
Maybe I didn't make the requirements 100% clear.
The OuterObject type and InnerObject type are just examples. We have several of these types (over 400), which can be nested in different combinations. It's not always the case that the InnerObject is nested within the OuterObject. The InnerObject could also be the root of another response of a different endpoint or be nested in another object than OuterObject.
Because of this requirement I don't see how I could solve that using @JsonView annotation. How would I define the views for the case that the OuterObject and InnerObject type can be either root or nested objects. I think I would end up with creating one view per root-to-nested object combination. Having over 400 of these objects this would probably explode in complexity.