I have the following controller returning a list of items from the database:
@GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public Page<Movies> getAll(Pageable pageable) {
return this.service.getAll(pageable);
}
As expected, Spring Boot serializes it correctly:
{
"content": [ ... ],
"pageable": { ... },
"last": false,
"totalPages": 2,
"totalElements": 35,
"size": 20,
"number": 0,
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"numberOfElements": 20,
"first": true,
"empty": false
}
However, I would like to rename one of these attributes. For example, I would like to use items
instead of content
as the key name.
In this case, since Page
is from org.springframework.data.domain
, I cannot use a Jackson annotation to rename the property.
I could write a custom serializer (something like this), but I just want to rename the attribute, so I do not want to write it from scratch.
What could be a better approach to handle this issue?
CodePudding user response:
You can use Mix-ins for that. You need an interface or abstract class where to apply the changes intended to the unmodifiable class:
interface MixIn<T> {
@JsonProperty("items")
List<T> getContent(); // rename property
}
and then register the Mix-in:
mapper.addMixIn(Slice.class, MixIn.class);
Slice
is the actual class where the content
property lives.
It will produce something like:
{
"last":true,
"totalElements":1,
"totalPages":1,
"size":0,
"number":0,
"numberOfElements":1,
"first":true,
"sort":null,
"items":[
"listItem"
]
}
CodePudding user response:
Another possibility would be to extend PageImpl
and adding items
attribute. Then you would need to map PageImpl
object to your custom object leaving content
empty by moving the content to items
.
Not really sure if this is better than writing a custom serializer but at least this is another approach.